SpringWeb注解 —— @RestControllerAdvice
RestControllerAdvice来捕获全局异常
@RestControllerAdvice都是对Controller进行增强的,可以全局捕获spring mvc抛的异常。
@ExceptionHandler(value = Exception.class)
ExceptionHandler的作用是用来捕获指定的异常。
@ExceptionHandler(value = Exception.class)
ExceptionHandler的作用是用来捕获指定的异常。
@RestControllerAdvice(annotations = RestController.class) public class UniformReponseHandler<T> { @ResponseStatus(HttpStatus.OK) public CallResultMsg sendSuccessResponse(){ return new CallResultMsg(true, CodeAndMsg.SUCCESS, null); } @ResponseStatus(HttpStatus.OK) public CallResultMsg sendSuccessResponse(T data) { return new CallResultMsg(true, CodeAndMsg.SUCCESS, data); } @ExceptionHandler(UserDefinedException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public CallResultMsg sendErrorResponse_UserDefined(Exception exception){ return new CallResultMsg(false, ((UserDefinedException)exception).getException(), null); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public CallResultMsg sendErrorResponse_System(Exception exception){ if (exception instanceof UserDefinedException) { return this.sendErrorResponse_UserDefined(exception); } return new CallResultMsg(false, CodeAndMsg.UNKNOWEXCEPTION, null); } }
通过上面的一波操作,我们的controller中就不需要再去写大量的try-catch了,RestControllerAdvice会自动帮助catch,并匹配相应的ExceptionHandler,然后重新封装异常信息,返回值,统一格式返回给前端。
ControllerAdvice 和 RestControllerAdvice的区别
@ControllerAdvice 和 @RestControllerAdvice都是对Controller进行增强的,可以全局捕获spring mvc抛的异常。
RestControllerAdvice = ControllerAdvice + ResponseBody
RestControllerAdvice = ControllerAdvice + ResponseBody
原文地址:https://www.jianshu.com/p/47aeeba6414c
一个小小后端的爬行痕迹