1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class BaseExceptionHandler {
private static final Log LOGGER = LogFactory.getLog(BaseExceptionHandler.class);
@ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity handle404Error(HttpServletRequest request, Throwable e){ LOGGER.error("@NoHandlerFound Path [{}] {}",request.getRequestURI(),e); return new ResponseEntity<>("400",e.getMessage(),null); }
@ExceptionHandler(ServerException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ResponseEntity handleError(HttpServletRequest request,Throwable e){ LOGGER.error("@Controller Path [{}] Method [{}]",request.getRequestURI(),request.getMethod()); LOGGER.error("@Error - ",e); return new ResponseEntity<>("4001","处理错误 | 错误原因 "+e.getMessage(),null); }
@ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class}) ResponseEntity handleMethodArgumentNotValidException(HttpServletRequest request, Exception e) { String message = "参数异常,"; if (e instanceof MethodArgumentNotValidException) { MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e; message = message + exception.getBindingResult().getFieldError().getDefaultMessage(); } else if (e instanceof BindException) { BindException exception = (BindException) e; message = message + exception.getBindingResult().getFieldError().getDefaultMessage(); } LOGGER.error("Controller Check Argument ErrorMsg:[{}] Path:[{}]", message, request.getRequestURI()); LOGGER.error("Controller Check Argument Error - ", e); return new ResponseEntity<>("4001", message, null); }
@ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) ResponseEntity handleControllerException(HttpServletRequest request, Throwable th) { LOGGER.error("Controller Path:[{}]", request.getRequestURI()); LOGGER.error("Controller Error - ", th); return new ResponseEntity<>("500", "操作错误,请稍后再试", null); } }
|