业务场景
统一处理try-catch的异常,并记录日志
代码
BaseBigRuntimeException
import com.alibaba.fastjson.JSON;
import com.watsons.onstore.common.vo.RestResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 运行时异常封装类
*/
public class BaseBigRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
protected static Map<String, String> mapMessage = new HashMap();
public static final String SYSTEM_INTERNAL_ERROR = "10001";
public static final String PARAMETER_ERROR = "10002";
public static final String RECORD_DUPLICATED = "11001";
public static final String RECORD_NOTEXIST = "11002";
public static final String APIGATEWAY_ERROR = "99999";
protected String code;
protected String rawMessage;
public BaseBigRuntimeException(String message) {
this("10001", message);
}
public BaseBigRuntimeException(String message, Throwable e) {
this("10001", message, e);
}
public BaseBigRuntimeException(String code, String message) {
super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\"}");
this.code = null;
this.rawMessage = null;
this.code = code;
this.rawMessage = message;
}
public BaseBigRuntimeException(String code, String message, Throwable e) {
super("{\"code\":\"" + code + "\", \"message\":\"" + message + "\"}", e);
this.code = null;
this.rawMessage = null;
this.code = code;
this.rawMessage = message;
}
public String getCode() {
return this.code;
}
public String getRawMessage() {
return this.rawMessage;
}
public String toRestResponseJson() {
return JSON.toJSONString(new RestResponse(this.code, this.rawMessage));
}
public static String getMessage(int code) {
return (String)mapMessage.get(code);
}
static {
mapMessage.put("10001", "系统内部错误");
mapMessage.put("10002", "业务参数异常");
mapMessage.put("11001", "记录重复");
mapMessage.put("11002", "记录不存在");
}
}
BigException
/**
* 业务异常封装
*/
public class BigException extends BaseBigRuntimeException {
public BigException(String info) {
super(ExceptionCode.FAIL.getCode(), info);
}
public BigException(String code, String info) {
super(code, info);
}
}
ExceptionCode
/**
* 异常错误编码
*/
public enum ExceptionCode {
/**
* 异常错误编码
*
* */
SYSTEM_ERROR("000000", "系统异常" +
""),
SUCCESS("0", "操作成功"),
FAIL("100000", "操作失败"),
// NOT_SUPPORTED("100001", "渠道不支持该接口"),
INVOKE("-2", "接口调用失败"),
VALIDATION_FAIL("1000", "数据验证失败"),
INVALID_PARAM("2000", "参数不合法"),
PARAM_EMPTY_ERROR("2001", "参数不能为空"),
RECORD_NOT_EXIST("3000", "记录不存在"),
AUTH_ERROR("4008", "缺失参数auth");
private final String code;
private final String msg;
ExceptionCode(String val, String info) {
this.code = val;
this.msg = info;
}
public void throwBizException() {
throw new BigException(this.getCode(), this.getMsg());
}
public String getCode() {
return this.code;
}
public String getMsg() {
return this.msg;
}
}
BaseControllerAdvice(捕获异常类)
记得在启动类上的@ComponentScan,扫描BaseControllerAdvice
import com.watsons.onstore.common.exception.BigException;
import com.watsons.onstore.common.exception.ExceptionCode;
import com.watsons.onstore.common.vo.RestResponse;
import com.watsons.onstore.framework.logs.OsLog;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
@RestControllerAdvice
public class BaseControllerAdvice {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
RestResponse handleException(Exception e) {
logger.error(e.getMessage(), e);
return new RestResponse(ExceptionCode.SYSTEM_ERROR.getCode(), ExceptionCode.SYSTEM_ERROR.getMsg());
}
@ExceptionHandler(BigException.class)
RestResponse handleBusinessException(BigException e) {
logger.error(e.getMessage(), e);
return new RestResponse(e.getCode(), e.getRawMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
RestResponse handleException(MethodArgumentNotValidException e) {
StringBuffer sb = new StringBuffer();
List<FieldError> fieldErrorList = e.getBindingResult().getFieldErrors();
if (CollectionUtils.isNotEmpty(fieldErrorList)) {
boolean isFirst = true;
for (FieldError error : fieldErrorList) {
if (isFirst) {
isFirst = false;
}else {
sb.append(";");
}
sb.append(error.getDefaultMessage());
}
}
String errorMsg = sb.toString();
logger.error(errorMsg, e);
return new RestResponse(ExceptionCode.VALIDATION_FAIL.getCode(), errorMsg);
}
}