以前两篇文章 Spring-boot自定义参数校验注解和如何在spring-boot中进行参数校验,咱们介绍了,参数校验以及如何自定义参数校验注解,可是当传递参数出错时,只是把错误信息打印到了控制台,合理的作法是应该把校验的错误信息返回给前端,告知用户那里有问题,下面就这一步内容进行说明。html
上篇文章 Spring-boot自定义参数校验注解的最后,在控制台打印了校验出错的信息前端
出错的异常类是MethodArgumentNotValidException
,那若是想要自定义异常的返回,就须要在全局的异常处理器中针对这种异常进行处理。java
在这篇文章 spring-boot自定义异常返回中,咱们说了如何进行自定义异常的返回,参数校验的错误信息返回依然按照此方式进行处理,在全局异常处理类中定义异常处理方法:spring
@ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public UnifyResponse handlerBeanValidationException(HttpServletRequest request, MethodArgumentNotValidException ex) { String requestUri = request.getRequestURI(); String method = request.getMethod(); List<ObjectError> errors = ex.getBindingResult().getAllErrors(); return UnifyResponse.builder() .code(5000) .message(formatError(errors)) .requestUri(method + " " + requestUri) .build(); } private String formatError(List<ObjectError> errors) { StringBuilder builder = new StringBuilder(); errors.forEach(error -> builder.append(error.getDefaultMessage()).append(";")); return builder.toString(); }
咱们来对上面的代码进行一下解释:app
@ExceptionHandler(value = MethodArgumentNotValidException.class)
这里指定List<ObjectError> errors = ex.getBindingResult().getAllErrors()
进行参数校验的时候,可能多个参数都有问题,咱们但愿可以有问题的参数的错误信息所有都返回回去,因此这里要获取全部的错误。回顾一下参数的定义,对这里有疑惑的同窗能够看一下这篇文章Spring-boot自定义参数校验注解函数
@Builder @Getter @Setter @PasswordEqual(min = 5, message = "密码和确认密码不同") public class UserDto { private int userId; @Length(min = 2, max = 10, message = "用户名长度必须在2-10的范围内") private String username; private String password; private String confirmPassword; }
接下来咱们定再定义一个简单的接口,当传参出错时看异常处理方法可否按照定义的那样返回错误信息spring-boot
@RequestMapping("/v2/user/create") public UserDto createUser(@RequestBody @Validated UserDto userDto){ return userDto; }
咱们先来构造一个密码和确认密码不一致的状况测试
能够看到定义的错误信息被返回,并且状态码和自定义的code都是符合设计的,接下来咱们再看一下多个参数错误的场景:ui
上面的场景中,用户名是不符合要求的,密码和确认密码也不同,因此会产生两条错误信息,将其拼接到一块儿,返回给前端。设计
以前讨论的都是body里提交的参数,接下来咱们看下路径参数或者查询参数校验出错时的处理
咱们先定义两个接口一个是路径参数查询信息,一个是经过查询参数查询信息
@GetMapping("/v2/user/info") public UserDto getUserInfo(@RequestParam @Length(min = 2, max = 5, message = "用户名长度必须在2-5的范围") String username){ return UserDto.builder() .userId(1000) .username(username) .build(); } @GetMapping("/v2/user/{username}") public UserDto getUserInfoV2(@PathVariable @Length(min = 2, max = 5, message = "用户名长度必须在2-5的范围") String username){ return UserDto.builder() .userId(2000) .username(username) .build(); }
而后咱们访问这两接口,当发生错误时,看看他们会不会进入上文定义的异常处理方法中:
很明显,并无进入上文定义的异常处理方法中,而是进入了handleException这个异常方法当中,这个算是个兜底的异常处理方法。
看一下控制台的输出:
这里抛出了ConstraintViolationException异常,这个异常咱们并无定制对应的异常处理函数,下面咱们就来写一下:
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public UnifyResponse handlerConstraintViolationException(HttpServletRequest request, ConstraintViolationException ex){ String requestUri = request.getRequestURI(); String method = request.getMethod(); Set<ConstraintViolation<?>> errors = ex.getConstraintViolations(); return UnifyResponse.builder() .code(6000) .message(formatConstraintException(errors)) .requestUri(method + " " + requestUri) .build(); } private String formatConstraintException(Set<ConstraintViolation<?>> constraintViolations){ StringBuilder builder = new StringBuilder(); constraintViolations.forEach(constraintViolation -> builder.append(constraintViolation.getMessage())); return builder.toString(); }
总体来讲异常处理和上文几乎是同样的,只是获取错误message的方式不同而已,咱们再请求一下:
至此参数校验的错误message自定义返回,都完成了。
本文连接:https://www.immortalp.com/articles/2020/05/16/1589623786527.html
欢迎你们去 个人博客 瞅瞅,里面有更多关于测试实战的内容哦!!