异常处理

应用场景

  1. 接口返回值

异常枚举类

public enum ResultCode {

    /**
     * 成功
     */
    SUCCESS(200, "接口调用成功"),

    /**/
    SIGN_ERROR(300,"验签失败"),
    INNER_SERVER_ERROR(500, "服务器内部错误"),
    UNAUTHORIZED(401, "Unauthorized"),
    /**/
    PAY_EXPIRED(1001, "超时"),
    DUPLACATE_REQ(1002, "重复提交"),
    PARAM_VALIDATE_FAIL(1003, "参数错误"),
    RESOURCE_NOT_EXISTS(1004, "资源不存在"),
    ;

    public final int code;

    public final String msg;

    public SystemException exception() {
        return new SystemException(this.code, this.msg);
    }

    public SystemException exception(String msg) {
        return new SystemException(this.code, msg);
    }

    public SystemException exception(Throwable cause) {
        return new SystemException(this.code, this.msg, cause);
    }

    public SystemException exception(String msg, Throwable cause) {
        return new SystemException(this.code, msg, cause);
    }
}

业务异常类

@Getter
public class SystemException extends RuntimeException {
    private int code = 500;

    private HashMap<String, Object> value;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public SystemException() {
    }

    public SystemException(int code) {
        this.code = code;
    }

    public SystemException(int code, String message) {
        super(message);
        this.code = code;
    }

    public SystemException(int code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

    public SystemException(Throwable cause) {
        super(cause.getMessage(), cause);
    }

    public SystemException(String pattern, Object[] args, Throwable cause) {
        super(String.format(pattern, args), cause);
    }

    public SystemException(int code, String pattern, Object[] args, Throwable cause) {
        super(String.format(pattern, args), cause);
        this.code = code;
    }

    public SystemException(int code, String pattern, Object... args) {
        super(String.format(pattern, args));
        this.code = code;
    }

    public SystemException(String pattern, Object[] args) {
        super(String.format(pattern, args));
    }

    public SystemException(String message) {
        super(message);
    }

    public SystemException(String message, Throwable cause) {
        super(message, cause);
    }

    public void setValue(HashMap<String, Object> value) {
        this.value = value;
    }
}

统一异常处理器

/**
 * 统一异常处理注册器
 */
@ControllerAdvice(annotations = RestController.class)
public class ExceptionRegister {
    private LoadingCache<String, Logger> LOGGER = CacheBuilder.newBuilder()
            .build(new CacheLoader<String, Logger>() {
                @Override
                public Logger load(String key) throws Exception {
                    return LoggerFactory.getLogger(key);
                }
            });


    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RestResult<?> handleSystemException(
            HttpServletRequest request, HttpServletResponse response, SystemException ex) {
        getLogger(ex).warn(ex.getMessage());
        if (ex.getValue() != null) {
            return new RestResult<>(ex.getCode(), ex.getMessage(), ex.getValue());
        }
        return new RestResult<>(ex.getCode(), ex.getMessage(), Maps.newHashMap());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RestResult<?> handleException(
            HttpServletRequest request, HttpServletResponse response, Exception ex) {
        getLogger(ex).error(ex.getMessage(), ex);
        return new RestResult<>(500, "Server Err", Maps.newHashMap());
    }

    private Logger getLogger(Exception ex) {
        StackTraceElement traceElement = ex.getStackTrace()[0];
        return LOGGER.getUnchecked(traceElement.getClassName());
    }
}

使用举例

// 抛出带返回值的业务异常
SystemException exception = ResultCode.ALREADY_PAY_SUCCESS.exception(e.getErrorMessage(), e);
HashMap<String, Object> map = Maps.newHashMap();
map.put("tradeOrderId", tradeOrderId);
exception.setValue(map);
throw exception;
// 抛出普通业务异常
throw ResultCode.REFUND_SUCCESS.exception();
This entry was posted in 编程工具. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.