MethodArgumentNotValidException参数校验异常
来源:3-11 利用切面类向客户端返回新令牌

魏榕汘
2022-09-02
老师您好,这是你的代码:
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public String validExceptionHandler(Exception e) {
log.error("执行异常",e);
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
//将错误信息返回给前台
return exception.getBindingResult().getFieldError().getDefaultMessage();
}
之前也学过一个类似的参数校验异常。代码是这样的:
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public ApiRestResponse handleMethodArgumentNotValidException(
MethodArgumentNotValidException e) {
log.error("MethodArgumentNotValidException: ", e);
return handleBindingResult(e.getBindingResult());
}
private ApiRestResponse handleBindingResult(BindingResult result) {
//把异常处理为对外暴露的提示
List<String> list = new ArrayList<>();
if (result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
for (ObjectError objectError : allErrors) {
String message = objectError.getDefaultMessage();
list.add(message);
}
}
if (list.size() == 0) {
return ApiRestResponse.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR);
}
return ApiRestResponse
.error(ImoocMallExceptionEnum.REQUEST_PARAM_ERROR.getCode(), list.toString());
}
想问老师:以上两个有什么区别???我看你写的更简单,谢谢!
写回答
1回答
-
神思者
2022-09-02
你那个是无条件获取任何异常里面的Message,但是不同类型异常的信息不是简单Get出来的。比如说后端验证的异常信息,提取就很复杂,不同类型的异常要区分对待
00