@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
// 日志
Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
/**
* 将异常在Controller捕获转换成Result对象返回
* @param ex
* @see Result
*/
@ExceptionHandler(Exception.class)
public Result handleAllException(Exception ex){
logger.error("ExceptionAdvice.handleAllException",ex);
// 返回统一的error Result
return Result.getErrorResult();
}
/**
* 处理ConstraintViolationException
* @param ex
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
public Result handleConstraintViolationException(ConstraintViolationException ex){
Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
ConstraintViolation<?> violation = violations.iterator().next();
String message = violation.getMessage();
logger.error("ExceptionAdvice.handleConstraintViolationException=>{}",message,ex);
return Result.getErrorResult();
}
}
```