springmvc三十:异常处理流程
生活随笔
收集整理的這篇文章主要介紹了
springmvc三十:异常处理流程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
handlerExceptionResolvers 異常解析也是springmvc的9大組件之一。
?
DispatcherServlet.properties中默認的異常解析如下:
org.springframework.web.servlet.HandlerExceptionResolver=
? ? org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver 處理@ExceptionHandler
?? ?org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver 處理@ResponseStatus,?@ResponseStatus標注在自定義異常類上
?? ?org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 判斷是否SpringMVC自帶的異常
?
package com.atchina;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;@Controller public class ExceptionTestController {@RequestMapping("/handler01")public String handler01(Integer i){System.out.println(10/i);return "success";}/*** 告訴SpringMVC這個方法專門處理這個類發生的異常 * 1. 給方法寫一個Exception,接受發生的異常* 2. 返回ModelAndView*/@ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})public ModelAndView handleException01(Exception exception){ModelAndView andView = new ModelAndView("myerror");andView.addObject("ex", exception);return andView;} }? 全局異常處理類
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView;// 集中處理所有異常的類加入到ioc容器中 // @ControllerAdvice專門處理異常的類 @ControllerAdvice public class MyGlobalException {@ExceptionHandler(value={ArithmeticException.class,NullPointerException.class})public ModelAndView handleException01(Exception exception){ModelAndView andView = new ModelAndView("myerror");andView.addObject("ex", exception);return andView;} }?使用HttpStatus
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus;@ResponseStatus(reason="用戶名不正確", code=HttpStatus.NOT_ACCEPTABLE) public class UserNameNotFoundException extends RuntimeException{private static final long serialVersionUID = 1L;}? 測試
@RequestMapping("/handler02")public String handler02(@RequestParam("username")String username){if(!"admin".equals(username)){throw new UserNameNotFoundException();}return "success";}?
總結
以上是生活随笔為你收集整理的springmvc三十:异常处理流程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springmvc二十九:拦截器
- 下一篇: springmvc三十一:spring