Spring Boot 3.x特性-自定义FailureAnalyzer

本文详细介绍了如何在Spring Boot应用中自定义FailureAnalyzer,通过ArithmeticExceptionFailureAnalyzer捕获并包装CustomerFailException异常,提升异常消息可读性。关键步骤包括创建自定义Analyzer、注册到spring.factories文件和应用启动配置。

自定义FailureAnalyzer

FailureAnalyzer拦截Spring Boot程序启动异常,将异常信息包装成可读性更好的消息,并且包装成FailureAnalysis对象。Spring Boot默认提供了大量的FailureAnalyzer
在这里插入图片描述

如果要实现自定义的FailureAnalyzer,只需要实现AbstractFailureAnalyzer抽象类,接下来先模拟程序启动异常。

public class CustomerFailException extends RuntimeException {
}
@SpringBootApplication
public class CustomerFailureanalyzerApplication {


    public static void main(String[] args) {
        SpringApplication.run(CustomerFailureanalyzerApplication.class, args);
    }

    @Bean
    public TestBean testBean() {
        return new TestBean();
    }

    class TestBean {
        public TestBean() {
            throw new CustomerFailException();
        }
    }
}

程序启动报错如下:

在这里插入图片描述

接下来自定义FailureAnalyzer,处理CustomerFailException异常。

  1. 创建自定义 FailureAnalyzer 继承 AbstractFailureAnalyzer
public class ArithmeticExceptionFailureAnalyzer extends AbstractFailureAnalyzer<CustomerFailException> {
    @Override
    protected FailureAnalysis analyze(Throwable rootFailure, CustomerFailException cause) {
        return new FailureAnalysis(cause.getMessage(), "检测Bean初始化是否正常!", cause);
    }
}

2.注册自定义FailureAnalyzer,在resources目录新建 META-INF/spring.factories文件,添加如下内容:

org.springframework.boot.diagnostics.FailureAnalyzer=com.example.customerfailureanalyzer.ArithmeticExceptionFailureAnalyzer

3.启动应用程序
在这里插入图片描述
注意:main线程抛出的异常无法处理,如下例子:

@SpringBootApplication
public class CustomerFailureanalyzerApplication {


    public static void main(String[] args) {
        TestBean testBean=new TestBean();
        SpringApplication.run(CustomerFailureanalyzerApplication.class, args);
    }
    static class TestBean {
        public TestBean() {
            throw new CustomerFailException();
        }
    }
}

启动程序:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

laopeng301

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值