Java自定义异常类以及异常拦截器

本文介绍如何在SpringBoot项目中自定义异常类及异常拦截器,实现统一异常处理,包括自定义异常类BingException的创建,及异常拦截器类ExceptionHandle的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  自定义异常类不难,但下面这个方法,它的核心是异常拦截器类。
  就算是在分布式系统间进行传递也可以,只要最顶层的服务有这个异常拦截器类(下例是在 springboot 项目中)

1、自定义异常类,继承自 RuntimeException,参数只有一个异常错误码

public class BingException extends RuntimeException {
    private final int code;

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

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

    public String getMessage() {
        return this.toString();
    }

    public String toString() {
        return "系统异常,异常编码:" + this.code;
    }
}

 

2、异常拦截器类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author jiashubing
 * @since 2018/10/29
 */
@ControllerAdvice
public class ExceptionHandle {

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

    /**
     * 异常处理
     * @param e 异常信息
     * @return 返回类是我自定义的接口返回类,参数是返回码和返回结果,异常的返回结果为空字符串
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        //自定义异常返回对应编码
        if (e instanceof BingException) {
            BingException ex = (BingException) e;
            return new Result<>(ex.getCode(), "");
        }
        //其他异常报对应的信息
        else {
            logger.info("[系统异常]{}", e.getMessage(), e);
            return new Result<>(-1, "");
        }

    }
}

 

3、然后在代码里抛异常就可以直接抛出异常了

throw new BingException(5);

 

原创文章,欢迎转载,转载请注明出处!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值