SpringMVC 中 @ControllerAdvice 注解的三种使用场景!
@ControllerAdvice ,很多初学者可能都没有听说过这个注解,实际上,这是一个非常有用的注解,顾名思义,这是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:
- 全局异常处理
- 全局数据绑定
- 全局数据预处理
灵活使用这三个功能,可以帮助我们简化很多工作,需要注意的是,这是 SpringMVC 提供的功能,在 Spring Boot 中可以直接使用,下面分别来看。
转载:https://www.cnblogs.com/lenve/p/10748453.html
应用:
@ControllerAdvice
@RestController
@Slf4j
public class GlobalExceptionHandler {
/**
* 自定义业务/数据异常处理
*
* @param exception
* @return
*/
@ExceptionHandler(value = {SpringBootPlusException.class})
@ResponseStatus(HttpStatus.OK)
public ApiResult<Boolean> springBootPlusExceptionHandler(SpringBootPlusException exception) {
printRequestDetail();
log.error("springBootPlusException:", exception);
int errorCode;
if (exception instanceof BusinessException) {
errorCode = ApiCode.BUSINESS_EXCEPTION.getCode();
} else if (exception instanceof DaoException) {
errorCode = ApiCode.DAO_EXCEPTION.getCode();
} else if (exception instanceof VerificationCodeException) {
errorCode = ApiCode.VERIFICATION_CODE_EXCEPTION.getCode();
} else {
errorCode = ApiCode.SPRING_BOOT_PLUS_EXCEPTION.getCode();
}
return new ApiResult<Boolean>()
.setCode(errorCode)
.setMessage(exception.getMessage());
}
}