歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> SpringMVC 異常處理

SpringMVC 異常處理

日期:2017/3/1 9:28:20   编辑:Linux編程

Using HTTP Status Codes

在我們自定義的異常上使用ResponseStatus注解。當我們的Controller拋出異常,並且沒有被處理的時候,他將返回HTTP STATUS 為指定值的 HTTP RESPONSE,比如:

    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
    public class OrderNotFoundException extends RuntimeException {
        // ...
    }

我們的Controller為:

 @RequestMapping(value="/orders/{id}", method=GET)
    public String showOrder(@PathVariable("id") long id, Model model) {
        Order order = orderRepository.findOrderById(id);
        if (order == null) throw new OrderNotFoundException(id);
        model.addAttribute(order);
        return "orderDetail";
    }

這時候會返回404,轉到404頁面而不是錯誤頁面

Controller Based Exception Handling

在一個Controller中,

,注意這種只在單個Controller中有效。這麼做可以:

  1. 發生異常後,改變Response status,一般而言,發生異常返回HTTP STATUS 500.我們可以變為其他。
  2. 發生錯誤後轉到錯誤頁面
  3. 可以為不同異常定義不同處理(如不同的錯誤頁面,不同的Response status)

舉例說明

@Controller
public class ExceptionHandlingController {

  // 我們標注了@RequestMapping的方法
  ...
  
  //處理異常的方法。
  
  // 把我們定義的異常轉換為特定的Http status code
  @ResponseStatus(value=HttpStatus.CONFLICT, reason="Data integrity violation")  // 409
  @ExceptionHandler(DataIntegrityViolationException.class)
  public void conflict() {
    // Nothing to do
  }
  

  // 捕獲到SQLException,DataAccessException異常之後,轉到特定的頁面。
  @ExceptionHandler({SQLException.class,DataAccessException.class})
  public String databaseError() {
    //僅僅轉到錯誤頁面,我們在頁面上得不到這個Exception的值,要得到值,我們可以通過下面的方法得到
    return "databaseError";
  }

  // 通過ModelAndView返回頁面,以及往頁面傳相應的值
  @ExceptionHandler(Exception.class)
  public ModelAndView handleError(HttpServletRequest req, Exception exception) {
    logger.error("Request: " + req.getRequestURL() + " raised " + exception);

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", exception);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("error");
    return mav;
  }
}

Global Exception Handling

在類上使用 @ControllerAdvice注解,可以使得我們處理整個程序中拋出的異常。


舉例:

class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
    
   //轉到特定頁面 。。。。。
}

如果我們要處理程序中所有的異常可以這麼做:


@ControllerAdvice
class GlobalDefaultExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it - like the OrderNotFoundException example
        // at the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
}

Going Deeper

實現HandlerExceptionResolver接口,SpringMvc可以使用他來處理Controller中拋出的異常

public interface HandlerExceptionResolver {
    ModelAndView resolveException(HttpServletRequest request, 
            HttpServletResponse response, Object handler, Exception ex);
}

SpringMvc使用三種默認的HandlerExceptionResolver來處理我們的異常

  1. ExceptionHandlerExceptionResolver:
  2. ResponseStatusExceptionResolver:
  3. DefaultHandlerExceptionResolver:把Spring定義的一些標准異常,轉換為HTTP STATUS CODE.

Spring內置的SimpleMappingExceptionResolver實現了HandlerExceptionResolver接口,也是我們經常使用的,XML配置如下:

<bean id="simpleMappingExceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <map>
                <!-- key為異常類型,value為要轉到的頁面 -->
                <entry key="DatabaseException" value="databaseError"/>
                <entry key="InvalidCreditCardException" value="creditCardError"/>
            </map>
        </property>
        <!-- 默認的異常頁面 -->
        <property name="defaultErrorView" value="error"/>
        <!-- 在頁面我們可以通過ex拿到異常信息 -->
        <property name="exceptionAttribute" value="ex"/>
        
        <!-- Name of logger to use to log exceptions. Unset by default, so logging disabled -->
         <!-- log異常信息,默認不設置-不記錄異常信息 -->
        <property name="warnLogCategory" value="example.MvcLogger"/>
    </bean>

Spring MVC+Spring3+Hibernate4開發環境搭建 http://www.linuxidc.com/Linux/2013-07/87119.htm

Spring MVC整合Freemarker基於注解方式 http://www.linuxidc.com/Linux/2013-02/79660.htm

基於注解的Spring MVC簡單介紹 http://www.linuxidc.com/Linux/2012-02/54896.htm

SpringMVC詳細示例實戰教程 http://www.linuxidc.com/Linux/2015-06/118461.htm

Spring MVC 框架搭建及詳解 http://www.linuxidc.com/Linux/2012-01/52740.htm

Copyright © Linux教程網 All Rights Reserved