Spring global exception handling with standalone app

本文分享了一种使用自定义全局异常处理程序的方法来捕获应用程序中未被捕获的异常。通过定义一个实现了UncaughtExceptionHandler接口的类,并将其设置为默认的异常处理器,可以有效地捕获并处理异常。然而,在实际应用中发现,某些情况下获取具体的错误消息存在局限性。

I have a standalone app, I need to catch all exceptions. There's one case that when I disconnect the internet, I couldn't connect the database, and database operations are in another component. It'll give me the exception. I was thinking to use a global exception handling, it did catch the exception but I couldn't get the exact error message. Finally, the easiest way is to use try..catch block.

Here I do want to share the global exception handling I found online.

The first step is to define your own UncaughtExceptionHandler implementation class.

import java.lang.Thread.UncaughtExceptionHandler;

public class CustomExceptionHandler implements UncaughtExceptionHandler
{
	public void uncaughtException(Thread t, Throwable e)
	{
		System.out.println("I caught an exception: " + e.getMessage());
	}
}

The second step is to set the default uncaught exception handler. 

public class Main
{
	public static void main(String[] args) throws Exception
	{
		Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());

		throw new Exception("I am exceptional!");
	}
}

It works on my case, the only thing is that e.getMessage() always return null on my case.


评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值