這篇文章主要介紹SpringMVC異常處理機制與自定義異常處理方式的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
提到異常處理,就不得不提HandlerExceptionResolvers,我們的DispatcherServlet默認設置三個異常處理器:
AnnotationMethodHandlerExceptionResolver:通過注解@ExceptionHandler實現異常理出
ResponseStatusExceptionResolver:通過注解@ResponseStatus處理HTTP請求的狀態碼異常
DefaultHandlerExceptionResolver:處理Spring Exception并將其轉換為HTTP響應狀態碼傳送的客戶端
| Exception | HTTP Status Code |
|---|---|
BindException | 400 (Bad Request) |
ConversionNotSupportedException | 500 (Internal Server Error) |
HttpMediaTypeNotAcceptableException | 406 (Not Acceptable) |
HttpMediaTypeNotSupportedException | 415 (Unsupported Media Type) |
HttpMessageNotReadableException | 400 (Bad Request) |
HttpMessageNotWritableException | 500 (Internal Server Error) |
HttpRequestMethodNotSupportedException | 405 (Method Not Allowed) |
MethodArgumentNotValidException | 400 (Bad Request) |
MissingServletRequestParameterException | 400 (Bad Request) |
MissingServletRequestPartException | 400 (Bad Request) |
NoHandlerFoundException | 404 (Not Found) |
NoSuchRequestHandlingMethodException | 404 (Not Found) |
TypeMismatchException | 400 (Bad Request) |
MissingPathVariableException | 500 (Internal Server Error) |
NoHandlerFoundException | 404 (Not Found) |
首先介紹的是注解@ResponseStatus
用于自定義異常類上
該異常屬于某種HTTP錯誤狀態碼異常(或者說交由其處理)
例如:我們自定義一個異常類:HttpStateCode404Exception,將其映射到404狀態碼
異常類:HttpStateCode404Exception.java
/**
*使用@ResponseStatus只能實現簡單的提示
*當程序中拋出HttpStateCode404Exception會使用提示語:頁面未找到
*/
@ResponseStatus(code=HttpStatus.NOT_FOUND,reason="頁面未找到")
public class HttpStateCode404Exception extends RuntimeException{
private static final long serialVersionUID = 1L;
}然后我們在一個Controller類處理/handleException/存在在的映射路徑時的處理方法
@Controller
@RequestMapping("handleException")
public class HandleExceptionController {
/*@ExceptionHandler({Throwable.class})
public String handleThisController(){
return "/handleException/404";
}*/
@RequestMapping("{url}")
public void handle404(){
throw new HttpStateCode404Exception();
}
}細心的讀者,一定會發現,我在上面注掉的代碼使用了@ExceptionHandler注解
最終我們可以得到錯誤頁面提示是這樣的:好丑,但是有我們的reason

此方式只能實現簡單的信息提示。
再來看看@ExceptionHandler
打開上面被注釋掉的代碼,你會發現我們的錯誤控制可以(轉發)跳轉頁面了。
而且由于我們的這個方法定義在這個Controller類中,只要滿足此@ExceptionHandler定義的異常都會走這個方法。
注意:是這個Controller類中所有請求出現異常,且異常被其包含
我希望定義一個全局異常處理呢???@ControllerAdvice
為我們實現處理所以的控制器Controllers的異常
具體實現
/**
* 定義一個處理所有Controllers的ExceptionHandler
*/
@ControllerAdvice
public class GlobalExceptionAdvice {
@ExceptionHandler({HttpStateCode404Exception.class})
public String handleThisController(){
return "/handleException/404";
}
/*處理其他異常...*/
}1.Controller處理時拋出異常
2.本Controller類中的@ExceptionHandler如果捕獲到,就執行其處理方法
3.否則,由全局異常捕獲處理
4.否則,由@ResponseStatus注解的異常捕獲處理
5.最后DefaultHandlerExceptionResolver處理
這恰恰也就是DispatcherServlet異常處理器的配置順序(循序調用,List)
SpringMVC當中的異常處理–自定義異常處理類
public class CustomerException extends Exception {
//定義我們的異常信息
private String exceptMsg;
public CustomerException(String exceptMsg){
this.exceptMsg = exceptMsg;
}
public String getExceptMsg() {
return exceptMsg;
}
public void setExceptMsg(String exceptMsg) {
this.exceptMsg = exceptMsg;
}
}import java.io.PrintWriter;
import java.io.StringWriter;
import javax.jws.WebParam.Mode;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class CustomerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {
//通過我們自定義異常處理器,繼承自HandlerExceptionResolver 來實現我們的異常處理
//自定義我們的異常信息
String msg = "";
//通過ModelAndView 來實現跳轉到我們的錯誤頁面,并且將錯誤信息帶回到頁面進行顯示
ModelAndView view = new ModelAndView();
view.setViewName("error");
//取出我們自定義的異常信息
if(ex instanceof CustomerException){
CustomerException exception = (CustomerException) ex;
msg = exception.getExceptMsg();
}else{
//獲取我們的stringWriter來獲取我們的異常信息
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
//通過ex.printStackTrace(printWriter);來向我們的printWriter當中輸入異常信息
ex.printStackTrace(printWriter);
msg = writer.toString();
}
//獲取到異常信息之后,通過短信,郵件等技術,通知相關人員
view.addObject("msg", msg);
return view;
}
}<!-- 申明我們的異常解析處理類--> <bean id="customerExceptionResolver" class="cn.itcast.springmvc.exception.CustomerExceptionResolver"></bean>
以上是“SpringMVC異常處理機制與自定義異常處理方式的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。