/**
* @author hhh
* @date 2019/1/17 16:28
* @Despriction
*/
@ResponseBody
@ControllerAdvice
@Log4j2
public class GlobalExceptionHandler {
/**
* 通用错误一般用于 catch 抛出异常的时候 详情见消息体
*/
public static final Integer GENERAL_ERROR = 604;
//处理通用异常
@ExceptionHandler(value = Exception.class)
public BaseResMessage defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
BaseResMessage<Entity> message = new BaseResMessage<>();
log.error("非捕获异常{}", e);
StackTraceElement[] stackTrace = e.getStackTrace();
StringBuilder sb = new StringBuilder("[系统错误!" + e.getClass().getName() + ": " + e.getLocalizedMessage() + "]\n");
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
String s = stackTraceElement.toString();
if (s.startsWith("com.jn")) {
sb.append(s).append("\n");
}
}
return message.error(GENERAL_ERROR, sb.toString());
}
@ExceptionHandler(CustomException.class)//可以将Exception中的异常信息以Json的信息返回给前端
public BaseResMessage handle(CustomException e) {
log.error("状态码:" + e.getErrorCode(), e);
return this.error(e);
}
public static BaseResMessage error(CustomException e) {
BaseResMessage baseResMessage = new BaseResMessage();
baseResMessage.setStatus(e.getErrorCode());
baseResMessage.setMsg(e.getMessage());
return baseResMessage;
}
}
public class CustomException extends RuntimeException {
private static final long serialVersionUID = 1L;
public static final Integer UNKNOWN_ERROR = -1;
/**
* 错误编码
*/
private int errorCode = UNKNOWN_ERROR;
/**
* 消息是否为属性文件中的Key
*/
private boolean propertiesKey = true;
/**
* 构造一个基本异常.
*
* @param message
* 信息描述
*/
public CustomException(String message)
{
super(message);
}
/**
* 构造一个基本异常.
*
* @param errorCode
* 错误编码
* @param message
* 信息描述
*/
public CustomException(int errorCode, String message)
{
this(errorCode, message, true);
}
/**
* 构造一个基本异常.
*
* @param errorCode
* 错误编码
* @param message
* 信息描述
*/
public CustomException(int errorCode, String message, Throwable cause)
{
this(errorCode, message, cause, true);
}
/**
* 构造一个基本异常.
*
* @param errorCode
* 错误编码
* @param message
* 信息描述
* @param propertiesKey
* 消息是否为属性文件中的Key
*/
public CustomException(int errorCode, String message, boolean propertiesKey)
{
super(message);
this.setErrorCode(errorCode);
this.setPropertiesKey(propertiesKey);
}
/**
* 构造一个基本异常.
*
* @param errorCode
* 错误编码
* @param message
* 信息描述
*/
public CustomException(int errorCode, String message, Throwable cause, boolean propertiesKey)
{
super(message, cause);
this.setErrorCode(errorCode);
this.setPropertiesKey(propertiesKey);
}
/**
* 构造一个基本异常.
*
* @param message
* 信息描述
* @param cause
* 根异常类(可以存入任何异常)
*/
public CustomException(String message, Throwable cause)
{
super(message, cause);
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public boolean isPropertiesKey()
{
return propertiesKey;
}
public void setPropertiesKey(boolean propertiesKey)
{
this.propertiesKey = propertiesKey;
}
}