Spring的基础
统一异常处理
如果在业务逻辑中出现异常,通常是在最外层的Controller中进行try catch捕获处理,但是这样每一个controller都需要进行try catch,而Spring提供了全局统一异常处理的方式处理拦截Controller中暴露的异常错误。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResultWrapper globalException() { return new ResultWrapper("全局错误码","全局异常"); } @ExceptionHandler(NullPointerException.class) public ResultWrapper customException(HttpServletResponse response,NullPointerException ex){ return new ResultWrapper("错误码","错误信息"); } }
|
参数校验
1 2 3 4 5 6 7
| @Data @Builder public class ResultWrapper<T>{ private String code; private String message; private T data; }
|
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
|
1 2 3 4 5 6 7 8 9 10 11 12
| @Data public class LoginDTO { @NotNull(message = "用户名不能为空") private String userName; @NotBlank(message = "密码不能为空") @Length(min = 6, message = "密码长度至少6位") private String password; @Email private String email; }
|
1 2 3 4 5 6 7 8
| @RestController public class LoginController { @PostMapping("/login") public ResultWrapper login(@RequestBody @Valid LoginDTO loginDTO) { return ResultWrapper(); } }
|
但是这样会直接将返回的message返回到前端,而不是我们定义的BaseResult返回格式,需要再进行一层结果集包装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @RestControllerAdvice public class GlobalExceptionAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class) public ResultWrapper methodArgumentNotValidException(MethodArgumentNotValidException e) { List<ObjectError> errors = e.getBindingResult().getAllErrors(); StringBuffer sb = new StringBuffer(); List<String> errorArr = Lists.newArrayList(); for (ObjectError error : errors) { if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; errorArr.add(fieldError.getField() + fieldError.getDefaultMessage()); } else { errorArr.add(error.getObjectName() + error.getDefaultMessage()); } } String errMsg = String.join(";", errorArr.toArray(new String[]{})); return new ResultWrapper("错误码xxx", errMsg); } }
|
全局异常处理类
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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| @ControllerAdvice public class GlobalExceptionAdvice {
@ResponseBody @ExceptionHandler({BusinessException.class}) public ResultWrapper bizException(BusinessException e) { log.error("出现异常:{}", e); return ResultWrapper.builder().code(e.getErrorCode()).msg(e.getMessage()).build(); }
@ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) public ResultWrapper methodArgumentNotValidException(MethodArgumentNotValidException e) { log.error("出现异常:{}", e); List<ObjectError> errors = e.getBindingResult().getAllErrors(); StringBuffer sb = new StringBuffer(); List<String> errorArr = Lists.newArrayList(); for (ObjectError error : errors) { if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; errorArr.add(fieldError.getField() + fieldError.getDefaultMessage()); } else { errorArr.add(error.getObjectName() + error.getDefaultMessage()); } } String errMsg = String.join(";", errorArr.toArray(new String[]{})); return ResultWrapper.builder().code(StateCodeEnum.METHOD_ARGUMENT_NOT_VALID.getCode()).msg(errMsg).build(); }
@ResponseBody @ExceptionHandler(ConstraintViolationException.class) public ResultWrapper constraintViolationException(ConstraintViolationException e) { log.error("出现异常:{}", e); StringBuffer sb = new StringBuffer(); List<String> errorArr = Lists.newArrayList(); for (ConstraintViolation constraint : e.getConstraintViolations()) { errorArr.add(constraint.getInvalidValue() + "非法" + constraint.getMessage()); } String errMsg = String.join(";", errorArr.toArray(new String[]{})); return ResultWrapper.builder().code(StateCodeEnum.CONSTRAINT_VIOLATION.getCode()).msg(errMsg).build(); }
@ResponseBody @ExceptionHandler(Exception.class) public ResultWrapper exception(Exception e) { log.error("出现异常:{}", e); return ResultWrapper.builder().code(StateCodeEnum.ERROR.getCode()).msg(e.getMessage()).build(); }
@ResponseBody @ExceptionHandler(HttpMessageConversionException.class) public ResultWrapper parameterTypeConvertException(HttpMessageConversionException e) { return ResultWrapper.builder().code(StateCodeEnum.ERROR.getCode()).msg(e.getMessage()).build(); } }
|