spring全局异常处理使用注解RestControllerAdvice
、ControllerAdvice
。
BindException
、MethodArgumentNotValidException
是hibernate校验失败抛出的异常。BasicException
是自定义的全局统一异常,其中属性error
可以提取出异常信息。
@RestControllerAdvice
public class BassExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(BassExceptionHandler.class);
@ExceptionHandler(value = BindException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST, code = HttpStatus.BAD_REQUEST)
public BassResult<String> handleBadParam(BindException ex) {
logger.error(ex.getMessage());
String result = ex.getBindingResult().getAllErrors().parallelStream().map(object -> object.getDefaultMessage())
.collect(Collectors.joining(", "));
return new BassResult<String>().builder().error(BassError.BAD_PARAM, result).build();
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST, code = HttpStatus.BAD_REQUEST)
public BassResult<String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
logger.error(ex.getMessage());
String result = ex.getBindingResult().getAllErrors().parallelStream().map(object -> object.getDefaultMessage())
.collect(Collectors.joining(", "));
return new BassResult<String>().builder().error(BassError.BAD_PARAM, result).build();
}
@ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE, code = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public BassResult<String> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
logger.error(ex.getMessage());
return new BassResult<String>().builder().error(BassError.UNSUPPORTED_MEDIA_TYPE, ex.getMessage()).build();
}
@ExceptionHandler(value = BassException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, code = HttpStatus.INTERNAL_SERVER_ERROR)
public BassResult<String> handleBasicException(BassException ex) {
logger.error(ex.toString());
return new BassResult<String>().builder().error(ex.getError(), ex.getMessage()).build();
}
@ExceptionHandler(value = Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, code = HttpStatus.INTERNAL_SERVER_ERROR)
public BassResult<String> handleException(Exception ex) {
logger.error(ex.getMessage());
return new BassResult<String>().builder().error(BassError.INTERNAL_SERVER_ERROR, ex.getMessage()).build();
}
}
网友评论