MethodArgumentNotValidException参数校验异常
之前也学过一个类似的参数校验异常。代码是这样的:
@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());想问老师:以上两个有什么区别???我看你写的挺复杂的,谢谢!
6
收起
正在回答 回答被采纳积分+1
1回答
java工程师2020版
- 参与学习 人
- 提交作业 9410 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星