1--依赖
<!--全局异常处理-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
2--配置
@Slf4j
@RestControllerAdvice
public class GlobalException {
/**
* 通用异常处理
*/
@ExceptionHandler(Exception.class)
public ResultJson labRunException(Exception e) {
log.error(e.getMessage(),e);
return ResultJson.error("系统异常:"+e.getMessage());
}
/**
* 实体接收参数校验 post MethodArgumentNotValidException,get BindException
* 单个接收参数 ConstraintViolationException
* @param e
* @return
*/
@ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class, ConstraintViolationException.class})
public ResultJson handleValidException(Exception e) {
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
return wrapperBindingResult(me.getBindingResult());
}
if (e instanceof BindException) {
BindException be = (BindException) e;
return wrapperBindingResult(be.getBindingResult());
}
if (e instanceof ConstraintViolationException) {
return wrapperConstraintViolationExceptionResult((ConstraintViolationException) e);
}
return ResultJson.error( "参数错误");
}
private ResultJson wrapperConstraintViolationExceptionResult(ConstraintViolationException e) {
StringBuilder msg = new StringBuilder();
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
if (CollectionUtils.isEmpty(constraintViolations)) {
return ResultJson.error( "参数错误");
}
for (ConstraintViolation<?> item : constraintViolations) {
String propertyPath = item.getPropertyPath().toString();
msg.append(", ").append(propertyPath.split("\\.")[1]).append(": ").append(item.getMessage());
}
return ResultJson.error( msg.substring(2));
}
private ResultJson wrapperBindingResult(BindingResult bindingResult) {
StringBuilder msg = new StringBuilder();
List<ObjectError> allErrors = bindingResult.getAllErrors();
if (CollectionUtils.isEmpty(allErrors)) {
return ResultJson.error("参数错误");
}
for (ObjectError error : allErrors) {
msg.append(", ");
if (error instanceof FieldError) {
msg.append(((FieldError) error).getField()).append(": ");
}
msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
}
return ResultJson.error(msg.substring(2));
}
}