Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Global Exception Handler - Not MVC

Tags:

java

spring

Does regular Spring (Boot) have a way to do global exception handling, or at least catch any uncaught exceptions (such as RuntimeException that may happen randomly)?

I've googled around, but everything I've found talked about the @ControllerAdvice @ExceptionHandler for controllers. Nothing about just a general global exception handler.

I basically just want to make sure that if some exception happens that I'm not already catching, that I log it so I know about it.

like image 877
samanime Avatar asked Dec 11 '17 14:12

samanime


People also ask

How do you handle exceptions in spring boot globally?

Exception Handler You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. Now, use the code given below to throw the exception from the API. The complete code to handle the exception is given below.

How do you handle exceptions in Spring MVC?

Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.

How do I create a global exception handler?

Adding a Global Exception HandlerType in a Name for the handler and save it in the project path. Click Create, a Global Exception Handler is added to the automation project.

How do you handle global exception in Microservices?

First, we need to set up the capability of throwing exceptions on core banking service errors. Open core banking service and follow the steps. Create a common exception class where we going to extend RuntimeException. After that, we can create custom runtime exceptions to use with this API.


2 Answers

Add your own via AOP, something like this will work:

@Aspect
@Component
public class ExceptionHandler {

    @AfterThrowing(pointcut = "within(*.*)", throwing = "t")
    public void log(Throwable t) {
        t.printStackTrace();
    }
}

Look at the cheat sheet to help with the pointcut.

like image 109
Essex Boy Avatar answered Sep 22 '22 22:09

Essex Boy


I think spring does not provide an out of the box solution for this.

A possibility to achieve this is using AOP with annotations (you may find an example here: Where can I catch non rest controller exceptions in spring?). With this approach, you can define a global pointcut for all the methods annotated with a pre-defined annotation. The good part of this approach is to have all the error handling logic in one place.

like image 24
pedrohreis Avatar answered Sep 20 '22 22:09

pedrohreis