自定义好处:
1、统一风格,方便定位问题;
2、方便控制异常流程。
第一步:创建一个自定义异常类,继承自RuntimeException,如下
package com.vlihub.common.exception;
import com.vlihub.common.enums.Codes;
/**
* 创建人: 537974(韦立)
* 创建时间: 2020-11-26 16:27
*/
public class VlihubException extends RuntimeException {
private Codes codes;
public VlihubException() {
super();
}
public VlihubException(String msg) {
super(msg);
this.codes = Codes.ERROR;
}
public VlihubException(Throwable e) {
super(e);
this.codes = Codes.ERROR;
}
public VlihubException(Codes codes) {
super(codes.getMsg());
this.codes = codes;
}
public VlihubException(Codes codes, String msg) {
super(msg);
this.codes = codes;
}
public Codes getCodes() {
return this.codes;
}
}
上面简单使用一个枚举型作为统一的返回编码。
第二步:处理异常,如下
package com.vlihub.common.exception;
import com.vlihub.common.configs.AppMailConfig;
import com.vlihub.common.enums.Codes;
import com.vlihub.common.helper.MailHelper;
import com.vlihub.common.model.vo.BaseResult;
import com.vlihub.common.model.vo.MailInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 创建人: 537974(韦立)
* 创建时间: 2020-11-26 16:31
*/
@ControllerAdvice
@ResponseBody
public class VlihubExceptionHandler {
@Resource
private MailHelper mailHelper;
@Resource
private AppMailConfig appMailConfig;
@ExceptionHandler(value = Exception.class)
public BaseResult exceptionHandler(Exception e) {
e.printStackTrace();
Thread th = new Thread(() -> sendErrorMail(e));
th.start();
if (e instanceof VlihubException) {
Codes code = ((VlihubException) e).getCodes();
return BaseResult.builder()
.code(code.getCode())
.title(Codes.ERROR.getMsg())
.message(e.getMessage())
.type(Codes.ERROR.toString().toLowerCase())
.build();
} else if (e instanceof NullPointerException) {
return BaseResult.error(e.getMessage(), Codes.ERROR_NULL_POINTER);
} else if (e instanceof DuplicateKeyException) {
return BaseResult.error(e.getMessage(), Codes.ERROR_SQL);
} else if (e instanceof IndexOutOfBoundsException) {
return BaseResult.error(e.getMessage(), Codes.ERROR_IDX_OUT_OF_BOUNDS);
} else if (e instanceof IllegalArgumentException) {
return BaseResult.error(e.getMessage(), Codes.ERROR_ILLEGAL_ARGUMENT);
}
return BaseResult.error(e.getMessage());
}
private void sendErrorMail(Exception e) {
MailInfo mailInfo = new MailInfo();
mailInfo.setTo(appMailConfig.getWarningTos());
mailInfo.setFrom(appMailConfig.getDefaultFrom());
mailInfo.setSubject("迈极集团-异常");
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
mailInfo.setText(sw.getBuffer().toString());
mailInfo.setIsHtml(true);
mailHelper.sendMail(mailInfo);
}
}
上面对异常做了简单处理,并且异常出现后发送邮件通知。