我們?cè)谧鯳eb應(yīng)用的時(shí)候隐轩,請(qǐng)求處理過(guò)程中發(fā)生錯(cuò)誤是非常常見(jiàn)的情況垢粮。通過(guò)使用@ControllerAdvice定義統(tǒng)一的異常處理類勾给,統(tǒng)一處理異常信息训柴。方便統(tǒng)一生成記錄錯(cuò)誤日志信息和異常處理哑舒。
先配置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("參數(shù)綁定異常", ex);
return new ObjectRestResponse().error(sb.toString());
}
@ResponseBody
@ExceptionHandler(ServiceException.class)
public ObjectRestResponse serviceExceptionExceptionHandler(ServiceException ex) {
log.error("系統(tǒng)業(yè)務(wù)異常", ex);
return ObjectRestResponse.error(ex.getMessage());
}
@ResponseBody
@ExceptionHandler(DataAccessException.class)
public ObjectRestResponse serviceExceptionExceptionHandler(DataAccessException ex) {
log.error("觸發(fā)數(shù)據(jù)只讀異常", ex);
return ObjectRestResponse.error("禁止操作此資源!");
}
@ResponseBody
@ExceptionHandler(Exception.class)
public ObjectRestResponse serviceExceptionExceptionHandler(Exception ex) {
log.error("系統(tǒng)未知異常", ex);
return ObjectRestResponse.error("系統(tǒng)異常,請(qǐng)聯(lián)系管理員幻馁!");
}
}
controller中使用
if(!EncryptUtil.decrypt(user.getPassword()).equals(password)){
throw new ServiceException("密碼不正確");
}