先贴出以前的:
public void saveQuestions(@RequestBody @Valid QuestionSaveRequest questionSaveRequest, BindingResult result){
//每次判断result很麻烦
}
如果每个校验方法都加上BindingResult ,个人觉得很麻烦,于是查了下资料,可以根据错误类型进行全局拦截
1:全局异常处理
@ControllerAdvice
public class BaseControllerExceptionHandler {
private Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 拦截业务异常
*/
@ExceptionHandler(StarException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ErrorTip notFount(StarException e) {
log.error("业务异常:", e);
return new ErrorTip(e.getCode(), e.getMessage());
}
/**
* 校验异常(参数请求错误),单独参数校验
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip paramReqError(ConstraintViolationException ex) {
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
List<String> msgList = new ArrayList<>();
while (iterator.hasNext()) {
ConstraintViolation<?> cvl = iterator.next();
String str[] = cvl.getPropertyPath().toString().split("\\.");
if (str.length > 0)
msgList.add(str[str.length - 1] + ":" + cvl.getMessage());
}
String msg = JSON.toJSONString(msgList, SerializerFeature.UseSingleQuotes);
log.error("请求异常:", ex);
return new ErrorTip(StarExceptionEnum.REQUEST_NULL.getCode(), msg);
}
/**
* 校验异常(参数请求错误)对象校验
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorTip bindException(MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex.getBindingResult();
String errorMesssage = "";
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage += fieldError.getField() + ":" + fieldError.getDefaultMessage() + ", ";
}
log.error("请求异常:", ex);
return new ErrorTip(StarExceptionEnum.REQUEST_NULL.getCode(), errorMesssage);
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFount(RuntimeException e) {
log.error("运行时异常:", e);
return new ErrorTip(StarExceptionEnum.SERVER_ERROR.getCode(), StarExceptionEnum.SERVER_ERROR.getMessage());
}
}
异常工具类:
public class ErrorTip {
protected int code;
protected String message;
public ErrorTip () {
}
public ErrorTip(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return this.code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
}
控制类中使用:
第一种:此种方式,对应异常ConstraintViolationException,需要在类头部加上注解 @Validated
public ResponseEntity<?> createAuthenticationToken(@Length(min = 1,max = 100) @RequestParam("userCode") String userCode) {
return ResponseEntity.ok();
}
第二种:对应异常MethodArgumentNotValidException
public void saveQuestions(@RequestBody @Valid QuestionSaveRequest questionSaveRequest){
}