一個簡單的全域性異常處理類
阿新 • • 發佈:2019-02-20
package cn.sayyoo.payserver.exception;
import cn.sayyoo.core.base.BaseException;
import cn.sayyoo.core.base.Result;
import cn.sayyoo.core.constant.ResultCode;
import cn.sayyoo.core.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全域性異常處理類
*
* @author yedeguo
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
/**
* 處理全部的異常的實現
*
* @param exception
* @return
* @throws Exception
*/
private Result dealException(Exception exception) throws Exception {
LOGGER.error("===============**出現異常啦出現異常啦! 出現異常啦出現異常啦!**================");
LOGGER.error("===============**開始處理異常**================");
exception.printStackTrace();
Result result = new Result<>();
if (exception instanceof BaseException) {
BaseException baseException = (BaseException) exception;
int code = baseException.getCode();
if (code == 0) {
code = ResultCode.ERROR_UNKNOW.getCode();
}
String message = baseException.getMessage();
if (StringUtil.isBlank(message)) {
message = ResultCode.ERROR_UNKNOW.getMessage();
}
result.setCode(code);
result.setMessage(message);
} else {
result.setCode(ResultCode.SYS_ERROR.getCode());
result.setMessage(exception.getMessage());
}
LOGGER.error("===============**異常處理完畢**================");
LOGGER.error("===============**出現異常啦出現異常啦! 出現異常啦出現異常啦!**================");
return result;
}
/**
* 所有異常報錯
*
* @param exception
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
public Result allExceptionHandler(Exception exception) throws Exception {
Result result = null;
try {
result = dealException(exception);
} catch (Exception e) {
LOGGER.error("出現了意料之外的異常,而且這個異常沒有被正確的處理");
e.printStackTrace();
}
//如果出現意料之外的錯誤,那麼直接返回系統錯誤
if (result == null) {
result = Result.error();
result.setMessage(ResultCode.SYS_ERROR.getMessage());
}
return result;
}
}