Spring global exception handling with standalone app

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.


你可能感兴趣的:(java,java,java,spring,spring,exception,exception,exception,APP,APP,standalone,standalone,handling)