Administrator
发布于 2019-11-08 / 1196 阅读
0
0

Spring Boot 重温(三) 统一异常处理

分析

目前的SpringBoot项目多用来开发APIs,提供统一的 response 信息就成了一个非常必要的需求,而在项目中总会有各种奇奇怪怪的 RuntimeException 出现,因为各种各样的原因, tester 在测试的时候可能不能完全重现,所以统一异常处理就十分有必要了,方便将程序出现异常时对 caller 提供友好的 response.

实现

SpringBoot 中提供了 @ControllerAdvice 为 Controller 中的异常实现统一处理。

// 自定义错误信息类
public class ErrorInfo {
    private String code;
    private String msg;
    ... setter & getter & Constructor ...
}

// 自定义异常
public class ApplicationException extends RuntimeException {
    private ErrorInfo errorInfo;
    ... setter & getter & Constructor ....
}

// 异常处理
@ControllerAdvice
public class ApplicationExceptionHandle {
    private static final ErrorInfo UNKNOWN = new ErrorInfo("999", "unknown error");

    @ExceptionHandler(ApplicationException.class)
    @ResponseBody
    public ResponseEntity<ErrorInfo> handleApplicationException(ApplicationException ex){
        return new ResponseEntity<ErrorInfo>(ex.getErrorInfo(), HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<ErrorInfo> handleApplicationException(Exception ex) {
        return new ResponseEntity<ErrorInfo>(UNKNOWN, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}


评论