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>