spring mvc全局异常处理,注解实现
生活随笔
收集整理的這篇文章主要介紹了
spring mvc全局异常处理,注解实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ssm框架中的異常處理,可以是dao, service, controller 一直拋出異常,拋出就完事了。最終由全局異常類捕獲,進行日志記錄,頁面跳轉。…
核心注解
// 方法級別 @ExceptionHandler // 全局異常類上 @ControllerAdvice // @ControllerAdvice + @ResponseBody @RestControllerAdvice自定義異常類
package cn.bitqian.exception; /*** define a exception class * @date 2020/11/9 11:33* @author echo lovely**/ public class MyException extends Exception {private static final long serialVersionUID = -3997793023922042500L;public MyException() {}public MyException(String msg) {super(msg);}public MyException(Throwable th) {super(th);}public MyException(String msg, Throwable th) {super(msg, th);}}局部異常處理,當前類有用
package cn.bitqian.controller;import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;/*** 局部捕捉異常優先!* @author echo lovely* @date 2020/11/9 11:55*/ @RestController public class DemoController {// 模擬空指針異常@GetMapping("/test1")public void test1(String str) {System.out.println(str.length());}// 捕捉當前controller 中的 空指針@ExceptionHandler(NullPointerException.class)public void nullPointerCatcher() {System.out.println("進入局部捕捉異常了。。");// 日志記錄// 頁面跳轉// 其它操作...}}全局異常處理類,捕捉公共的異常
package cn.bitqian.exception;import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody;/*** 全局異常處理器* @author echo lovely**/ @ControllerAdvice public class BaseExceptionHandler {// 收集空指針的異常@ExceptionHandler(NullPointerException.class)@ResponseBodypublic String nullPointerException(NullPointerException nullPointerException) {return "NullPointerException";}// 參數異常@ExceptionHandler(IllegalArgumentException.class)@ResponseBodypublic String illegalArgumentException(IllegalArgumentException illeagal) {return "IllegalArgumentException" + illeagal.getMessage();}// 自定義異常@ExceptionHandler(MyException.class)@ResponseBodypublic String myException(MyException e) {// 日志記錄,跳轉頁面return "MyException" + e.getMessage();}// 最大的異常@ExceptionHandler(Exception.class)@ResponseBodypublic String allException(Exception e) {return e.getMessage();}}bean配置請看:
https://blog.csdn.net/qq_44783283/article/details/108471951
異常映射處理器,當發生某種指定異常時,跳轉到指定頁面
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" ><!-- 默認的錯誤信息頁面--><property name="defaultErrorView" value=">/error.jsp"/><property name="exceptionMappings"><props><prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop></props></property> </bean>總結
以上是生活随笔為你收集整理的spring mvc全局异常处理,注解实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 选择排序的时间复杂度
- 下一篇: c++ 数组的输入遇到特定字符停止输入_