Springboot 全局异常捕获

来源:互联网 发布:淘宝网文具盒 编辑:程序博客网 时间:2024/05/16 16:20

Springboot 全局异常捕获

springboot 全局异常捕获,首先创建一个 SmaugExceptionUtil 用于捕获全局异常
代码如下

@ControllerAdvicepublic class SmaugExceptionUtil {    @ExceptionHandler(Exception.class)    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)    @ResponseBody    public ExceptionResponse handleException(HttpServletRequest request, Exception ex) {        String msg = ex.getMessage();        return ExceptionResponse.create(HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);    }}

写一个简单的例子

@RequestMapping(value = "exception", method = RequestMethod.POST)    public int exception() {        return 10 / 0;    }

postman 回调

{  "errMsg": "/ by zero",  "errNo": 500}

ExceptionResponse 详细代码

@Data@EqualsAndHashCode(callSuper = false)public class ExceptionResponse {    private int errNo;    private String errMsg;    private String stackTraceElement;    public ExceptionResponse(Integer code, String message, String stackTraceElement){        this.errMsg = message;        this.errNo = code;        this.stackTraceElement = stackTraceElement;    }    public static ExceptionResponse create(Integer code, String message, String stackTraceElement){        return new ExceptionResponse(code, message, stackTraceElement);    }}

注释 @ControllerAdvice是controller的一个辅助类,最常用的就是作为全局异常处理的切面类 并且 可以指定扫描范围

0 0
原创粉丝点击