Java全局异常处理

Java项目对系统抛出的异常做分类提示,或后续处理。

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //方法一:未细化异常,全部抓取
    @ExceptionHandler(Exception.class)
    public JSONObject handleException(Exception e, HttpServletRequest httpServletRequest) {
        //方法内部的样例和返回值类型可以根据需要自行定义
        log.error("系统异常{0}", e);
        JSONObject res = new JSONObject();
        String messageId = httpServletRequest.getHeader(Constant.MESSAGE_ID);
        res.put(Constant.STATUS, Constant.E);
        res.put(Constant.CODE, String.valueOf(ReturnT.FAIL_CODE));
        res.put(Constant.MESSAGE, "系统异常");
        res.put(Constant.MESSAGEID, messageId);
        res.put(Constant.REQUEUE, String.valueOf(false));
        return res;
    }

    //方法二:运行时异常
    @ExceptionHandler(RuntimeException.class)
    public JSONObject runtimeException(RuntimeException e, HttpServletRequest httpServletRequest) {
        //方法内部的样例和返回值类型可以根据需要自行定义

        return new JSONObject();
    }

    //方法三:自定义异常
    @ExceptionHandler({BaseException.class})
    public JSONObject baseException(BaseException e, HttpServletRequest httpServletRequest) {

        return new JSONObject();
    }
}

自定义异常类:

public class BaseException extends RuntimeException {

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值