Springboot 全局异常处理

0.ApiException

/**
 * controller exception annotation
 */
@Retention(RUNTIME)
@Target(METHOD)
public @interface ApiException {
    Status value();
}

1.配置全局异常处理

@ControllerAdvice
@ResponseBody
public class ApiExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ApiExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e, HandlerMethod hm) {
        ApiException ce = hm.getMethodAnnotation(ApiException.class);
        if (ce == null) {
            logger.error(e.getMessage(), e);
            return Result.errorWithArgs(Status.INTERNAL_SERVER_ERROR_ARGS, e.getMessage());
        }
        Status st = ce.value();
        logger.error(st.getMsg(), e);
        return Result.error(st);
    }
	// 可以自定义一个自己的异常类,然后捕获这个异常类,进行数据返回

}

2.全局异常处理,抛出Status.INTERNAL_SERVER_ERROR_ARGS错误信息

public enum Status {

    SUCCESS(0, "success", "成功"),

    INTERNAL_SERVER_ERROR_ARGS(10000, "Internal Server Error: {0}", "服务端异常: {0}"),
    FAILED(500,"Internal Server Error: {0}", "服务端异常: {0}"),
    QUERY_APP_SYS_FAILED(505, "query sys app failed", "查询系统应用失败"),
    CREATE_POD_ORDER_FAILED(10002, "create pod order failed", "创建POD申请单失败"),
    CREATE_RDS_ORDER_FAILED(10004, "create rds order failed", "创建RDS申请单失败"),
    MODIFY_RDS_ORDER_FAILED(10006, "modify rds order failed", "创建RDS变更单失败"),
    CREATE_REDIS_ORDER_FAILED(10005, "create redis order failed", "创建REDIS申请单失败"),
    QUERY_FLOW_FAILED(10003, "query flow order failed", "查询申请单失败"),
    CREATE_ES_ORDER_FAILED(10008, "create es order failed", "创建ES申请单失败"),
    QUERY_SUBNET_FAILED(10010, "query subnet failed", "查询子网失败,该地域无可用子网"),
    REPAIR_INSTANCE_FAILED(10019, "repair instance failed", "修复实例失败"),
    QUERY_INSTANCE_FAILED(10029, "query instance failed", "查询实例失败"),
    DATABASE_NAME_FAILED(10039, "database name failed", "必填项, 只支持数字、小写字母及英文下划线“_”,必须以字母开头,字母或数字结尾,且不少于2字符不超过32个字符"),
    ;

    private final int code;
    private final String enMsg;
    private final String zhMsg;

    private Status(int code, String enMsg, String zhMsg) {
        this.code = code;
        this.enMsg = enMsg;
        this.zhMsg = zhMsg;
    }

    public int getCode() {
        return this.code;
    }

    public String getMsg() {
        if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(LocaleContextHolder.getLocale().getLanguage())) {
            return this.zhMsg;
        } else {
            return this.enMsg;
        }
    }
}

3.统一返回结果Result对象

package fama.cost.api.utils;

import fama.cost.api.enums.Status;

import java.text.MessageFormat;

/**
 * result
 *
 * @param <T> T
 */
public class Result<T> {
    /**
     * status
     */
    private Integer code;

    /**
     * message
     */
    private String msg;

    /**
     * data
     */
    private T data;

    public Result() {
    }

    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result(T data) {
        this.code  = 0;
        this.data = data;
    }

    private Result(Status status) {
        if (status != null) {
            this.code = status.getCode();
            this.msg = status.getMsg();
        }
    }

    /**
     * Call this function if there is success
     *
     * @param data data
     * @param <T> type
     * @return resule
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    /**
     * Call this function if there is any error
     *
     * @param status status
     * @return result
     */
    public static Result error(Status status) {
        return new Result(status);
    }

    /**
     * Call this function if there is any error
     *
     * @param status status
     * @param args args
     * @return result
     */
    public static Result errorWithArgs(Status status, Object... args) {
        return new Result(status.getCode(), MessageFormat.format(status.getMsg(), args));
    }

    public Integer getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


    @Override
    public String toString() {
        return "Status{" +
                "code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}


posted @ 2021-06-01 10:47  SpecialSpeculator  阅读(187)  评论(0编辑  收藏  举报