spring全局异常抓取validation校验信息

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler({Exception.class})
@ResponseBody
public Object exception(Exception e, HttpServletRequest request, HttpServletResponse response) {

//参数校验get
if(e instanceof ConstraintViolationException){
StringBuffer sb = new StringBuffer();
ConstraintViolationException exs = (ConstraintViolationException)e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for(ConstraintViolation<?> item:violations){
sb.append(item.getMessage()+"/");
}
return new BaseRespBackEnd(101,"请求参数错误",sb.toString());
}

//参数校验post
if(e instanceof MethodArgumentNotValidException){
MethodArgumentNotValidException exs = (MethodArgumentNotValidException)e;
BindingResult bindingResult = exs.getBindingResult();
StringBuffer sb = new StringBuffer();
for(FieldError fieldError :bindingResult.getFieldErrors()){
sb.append(fieldError.getDefaultMessage()+"/");
}
return new BaseRespBackEnd(101,"请求参数错误",sb.toString());
}
}
}
posted @ 2018-08-01 11:05  剑小破  阅读(3067)  评论(0编辑  收藏  举报