一、概述
在spring 体系中,异常处理有如下:https://www.cnblogs.com/bjlhx/p/8666653.html
可以结合jsr303使用:https://www.cnblogs.com/bjlhx/p/10305344.html
二、请求参数类异常
结合以上两种以及上文api设计原则修改响应数据,将请求参数类异常定位到http响应吗为4XX类,如下
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = ConstraintViolationException.class) @ResponseBody public ResponseEntity constraintViolationExceptionHandler(Exception e) { Map<String,Object> result=new HashMap(); result.put("code",400); result.put("msg",e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } @ExceptionHandler(value = javax.validation.UnexpectedTypeException.class) @ResponseBody public ResponseEntity unexpectedTypeExceptionHandler(Exception e) { Map<String,Object> result=new HashMap(); result.put("code",400); result.put("msg",e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } @ExceptionHandler(value = org.springframework.http.converter.HttpMessageNotReadableException.class) @ResponseBody public ResponseEntity httpMessageNotReadableExceptionHandler(Exception e) { Map<String,Object> result=new HashMap(); result.put("code",400); result.put("msg","没有请求体,详细:"+e.getMessage()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } @ExceptionHandler(value = org.springframework.web.bind.MethodArgumentNotValidException.class) @ResponseBody public ResponseEntity methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) { Map<String,Object> result=new HashMap(); result.put("code",400); result.put("msg","请求体校验失败,详细:"+e.getMessage()); if (e.getBindingResult().hasErrors()) { List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); result.put("data",fieldErrors); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result); } @ExceptionHandler(value = Exception.class) public void errorHandler(Exception e,HttpServletResponse response) throws IOException { response.sendError(HttpStatus.BAD_REQUEST.value()); } }
可以参看:https://blog.jayway.com/2014/10/19/spring-boot-error-responses/