使用 @ControllerAdvice+ @ ExceptionHandler 注解
@ControllerAdvice
@Component
public class GlobalExceptionHandler {
/**
* 拦截 Exception 异常
*
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public ResponseBean handle(Exception e) {
//@Valid校验异常信息
if (e instanceof BindException) {
return ResponseBean.createError(((BindException) e).getFieldError().getDefaultMessage());
}
return ResponseBean.createException("捕获异常:" + e);
}
}