我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况。通过使用@ControllerAdvice定义统一的异常处理类,统一处理异常信息。方便统一生成记录错误日志信息和异常处理。
先配置ServiceException
public class ServiceException extends RuntimeException {
public ServiceException(String message, Throwable throwable) {
super(message, throwable);
}
public ServiceException(String message) {
super(message);
}
}
全局消息
@Data
public class ObjectRestResponse<T> {
boolean rel;
String msg;
T result;
public ObjectRestResponse() {
}
public ObjectRestResponse(String msg) {
this.msg = msg;
}
public static ObjectRestResponse success() {
return new ObjectRestResponse();
}
public static ObjectRestResponse success(String msg) {
return new ObjectRestResponse(msg);
}
public static ObjectRestResponse success(Object data) {
ObjectRestResponse jr = new ObjectRestResponse();
jr.setResult(data);
return jr;
}
public static ObjectRestResponse error() {
ObjectRestResponse jr = new ObjectRestResponse();
jr.setRel(false);
return jr;
}
public static ObjectRestResponse error(String msg) {
ObjectRestResponse jr = new ObjectRestResponse(msg);
jr.setRel(false);
return jr;
}
public ObjectRestResponse rel(boolean rel) {
this.setRel(rel);
return this;
}
public ObjectRestResponse msg(String msg) {
this.setMsg(msg);
return this;
}
public ObjectRestResponse result(T result) {
this.setResult(result);
return this;
}
}
配置ControllerAdvice
@Slf4j
@ControllerAdvice
public class ExceptionControllerAdvice {
@ResponseBody
@ExceptionHandler(BindException.class)
public ObjectRestResponse bindExceptionHandler(BindException ex) {
StringBuffer sb = new StringBuffer();
ex.getFieldErrors().forEach(fieldError -> sb.append(fieldError.getDefaultMessage()).append(","));
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
log.error("参数绑定异常", ex);
return new ObjectRestResponse().error(sb.toString());
}
@ResponseBody
@ExceptionHandler(ServiceException.class)
public ObjectRestResponse serviceExceptionExceptionHandler(ServiceException ex) {
log.error("系统业务异常", ex);
return ObjectRestResponse.error(ex.getMessage());
}
@ResponseBody
@ExceptionHandler(DataAccessException.class)
public ObjectRestResponse serviceExceptionExceptionHandler(DataAccessException ex) {
log.error("触发数据只读异常", ex);
return ObjectRestResponse.error("禁止操作此资源!");
}
@ResponseBody
@ExceptionHandler(Exception.class)
public ObjectRestResponse serviceExceptionExceptionHandler(Exception ex) {
log.error("系统未知异常", ex);
return ObjectRestResponse.error("系统异常,请联系管理员!");
}
}
controller中使用
if(!EncryptUtil.decrypt(user.getPassword()).equals(password)){
throw new ServiceException("密码不正确");
}