吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2228|回复: 30
收起左侧

[Java 原创] java全局异常统一处理

  [复制链接]
covenlonki 发表于 2023-8-10 17:59
java全局异常统一处理
[Java] 纯文本查看 复制代码
public interface MsgGlobal {
    /**
     * 成功
     */
    Integer SUCCESS_CODE = 0;
    String SUCCESS_MSG = "成功";

    /**
     * 失败
     */
    Integer FAILED_CODE = 10000;
    String FAILED_MSG = "系统执行错误";

    String JSON_PARSE_ERROR = "22001_Json 没有解析成功;请检查格式!";
}

/**
 * 响应结果
 **/
public class Result<T> implements Serializable {

    //返回的具体数据
    private T data;
    //错误码
    private Integer eCode;
    //错误信息
    private String eMsg;
    //是否成功
    private Boolean success;

    public static <T> Result<T> failed() {
        return result(MsgGlobal.FAILED_CODE, MsgGlobal.FAILED_MSG, null);
    }


    public static <T> Result<T> failed(String msg) {
        // 错误码切割 EXECUTION_ERROR = "20001_系统执行出错"
        int code = MsgGlobal.FAILED_CODE;
        String msgTemp = msg;
        if (!StringUtils.isEmpty(msg)) {
            String[] codeMsg = StringUtils.split(msg, "_");
            if (codeMsg.length > 1) {
                code = Integer.valueOf(codeMsg[0]);
                msgTemp = codeMsg[1];
            }
        }
        return result(code, msgTemp, null);
    }

    public static <T> Result<T> failed(String msg, T data) {
        int code = MsgGlobal.FAILED_CODE;
        String msgTemp = msg;
        if (!StringUtils.isEmpty(msg)) {
            String[] codeMsg = StringUtils.split(msg, "_");
            if (codeMsg.length > 1) {
                code = Integer.valueOf(codeMsg[0]);
                msgTemp = codeMsg[1];
            }
        }
        return result(code, msgTemp, data);
    }

    public static <T> Result<T> failed(Integer code, String msg) {
        return result(code, msg, null);
    }

    public static <T> Result<T> failed(Integer code, String msg, T data) {
        return result(code, msg, data);
    }

    public static <T> Result<T> judge(boolean status) {
        if (status) {
            return success();
        } else {
            return failed();
        }
    }

    private static <T> Result<T> result(Integer code, String msg, T data) {
        Result<T> result = new Result<T>();
        result.seteCode(code);
        result.setData(data);
        result.seteMsg(msg);
        return result;
    }

    public static <T> Result<T> success(T data, Long total) {
        Result<T> result = new Result();
        result.seteCode(MsgGlobal.SUCCESS_CODE);
        result.seteMsg(MsgGlobal.SUCCESS_MSG);
        result.setData(data);
        return result;
    }

    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> success(T data) {
        String msg = MsgGlobal.SUCCESS_MSG;
        Integer code = MsgGlobal.SUCCESS_CODE;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            msg = MsgGlobal.FAILED_MSG;
            code = MsgGlobal.FAILED_CODE;
        }
        return result(code, msg, data);
    }

    public T getData() {
        return data;
    }

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

    public Boolean getSuccess() {
        success = eCode == 0;
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public Integer geteCode() {
        return eCode;
    }

    public void seteCode(Integer eCode) {
        this.eCode = eCode;
    }

    public String geteMsg() {
        return eMsg;
    }

    public void seteMsg(String eMsg) {
        this.eMsg = eMsg;
    }
}

/**
 * 自定义异常
 **/
public class BizException extends RuntimeException {

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

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

    public BizException(Throwable cause){
        super(cause);
    }

    public static BizException from(String errorMsg) {
        return new BizException(errorMsg);
    }
}


/**
 * 全局异常处理
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Result handleBizException(BizException e) {
        log.error("业务异常,异常原因:{}", e.getMessage(), e);
        return Result.failed(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("未知异常,异常原因:{}", e.getMessage(), e);
        e.printStackTrace();
        return Result.failed(e.getMessage());
    }

    @ExceptionHandler({IllegalArgumentException.class, HttpMessageNotReadableException.class})
    public Result handleIllegalArgumentException(Exception e) {
        log.error("非法参数异常,异常原因:{}", e.getMessage(), e);
        if (e instanceof HttpMessageNotReadableException) {
            return Result.failed(MsgGlobal.JSON_PARSE_ERROR);
        }
        log.error("非法参数异常,异常原因:{}", e.getMessage(), e);
        return Result.failed(e.getMessage());
    }

    @ExceptionHandler(JsonProcessingException.class)
    public Result handleJsonProcessingException(JsonProcessingException e) {
        log.error("Json转换异常,异常原因:{}", e.getMessage(), e);
        return Result.failed(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数异常,异常原因:{}", e.getMessage(), e);
        return Result.failed(e.getFieldError().getDefaultMessage());
    }
}

直接捕获项目的异常,自定义异常统一处理返回友好提示语!

免费评分

参与人数 4吾爱币 +10 热心值 +3 收起 理由
junjia215 + 1 + 1 用心讨论,共获提升!
ningyaya + 1 我很赞同!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
wsdxdc1 + 1 + 1 谢谢@Thanks!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

yh2023 发表于 2023-8-10 20:41
谢谢分享
小丑恶人 发表于 2023-8-10 21:44
moruye 发表于 2023-8-10 22:00
sobani 发表于 2023-8-11 10:03
谢谢大佬,解决了困扰我许久的问题
wshuangh888 发表于 2023-8-11 11:02
以后会用得上!感谢分享!
JokerDa 发表于 2023-8-11 11:49
感谢分享!回头就去项目上试试
hope77 发表于 2023-8-15 09:30
可以的  学习了
dhaowei 发表于 2023-8-21 17:42
感谢楼主分享
nisar 发表于 2023-8-22 22:43
刚学java一星期,目前知道的只有main方法,这个是不是得放到代码目录下才行
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-28 19:43

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表