spring boot请求参数验证
场景:
在接口中经常需要对参数的合法性做验证,spring boot中提供了@Vaild注解,可以方便的完成验证。如何处理验证失败的返回类型,方便客户端调用。
解决思路:
在验证参数失败时,会抛出一个MethodArgumentNotValidException的异常,如果我们能捕获这个异常,那就可以把异常信息返回给客户端。
我们可以使用@RestControllerAdvice注解,对我们的Controller增强,捕获MethodArgumentNotValidException、HttpMessageNotReadableException以及我们自定义的ParamaErrorException。
实现:
@RestControllerAdvice("net.kisssoft.controllers")
public class ControllerExceptionAdvice {
/**
* 忽略参数异常处理器
*
* @param e 忽略参数异常
* @return ResponseResult
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
return Result.CreateFail("请求参数 " + e.getParameterName() + " 不能为空");
}
/**
* 缺少请求体异常处理器
*
* @param e 缺少请求体异常
* @return ResponseResult
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
return Result.CreateFail("参数体不能为空");
}
/**
* 参数效验异常处理器
*
* @param e 参数验证异常
* @return ResponseInfo
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result parameterExceptionHandler(MethodArgumentNotValidException e) {
BindingResult exceptions = e.getBindingResult();
// 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
if (exceptions.hasErrors()) {
List<ObjectError> errors = exceptions.getAllErrors();
if (!errors.isEmpty()) {
// 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
FieldError fieldError = (FieldError) errors.get(0);
return Result.CreateFail(fieldError.getDefaultMessage());
}
}
return Result.CreateFail("error");
}
/**
* 自定义参数错误异常处理器
*
* @param e 自定义参数
* @return ResponseInfo
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({ParamaErrorException.class})
public Result paramExceptionHandler(ParamaErrorException e) {
//log.error("", e);
// 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
if (!StringUtils.isEmpty(e.getMessage())) {
return Result.CreateFail(e.getMessage());
}
return Result.CreateFail("error");
}
}Result是我们通用的返回类型,当参数验证失败,我们返回400。并返回对应的类型。

浙公网安备 33010602011771号