在后端发生异常或者是请求出错时,前端通常显示如下:
本文主要讲解在SpringBoot中统一异常处理的方式:
第一种:使用 @ControllerAdvice
和 @ExceptionHandler注解
第二种: 实现 ErrorController
接口
-
第一种:使用
@ControllerAdvice
和@ExceptionHandler
注解,@ControllerAdvice
是一个控制器增强类,当Controller层发生异常且符合类中定义的异常类,将会被拦截,没有符合的异常类,将走系统默认的异常处理方式或自定义的异常处理类@Slf4j @RestControllerAdvice public class InternalExceptionHandler { @ExceptionHandler(Exception.class) public Result internalException(HttpServletResponse response,Exception e){ Result result = new Result(response.getStatus(), "Controller层抛出的异常", e.getMessage()); return result; } } 复制代码
-
第二种: 实现
ErrorController
接口,系统默认的错误处理类为BasicErrorController,将会显示如上的错误页面。这里编写一个自己的错误处理类,上面默认的处理类将不会起作用,getErrorPath()
将会重定向到处理异常的controller@RestController public class HttpErrorHandler implements ErrorController { private static final String ERROR_PATH="/error"; @RequestMapping(value = ERROR_PATH) public Result error(HttpServletResponse response,Exception e) { Result result = new Result(response.getStatus(), "全局异常", e.getMessage()); return result; } @Override public String getErrorPath() { return ERROR_PATH; } } 复制代码
测试:
@RestController
@RequestMapping
public class HelloConroller {
@GetMapping("/getMsg")
public String say(){
int a=10/0;
return "成功执行!";
}
}
复制代码