@ControllerAdvice Global Error Handling Example in Spring Boot

In this post, we will see @ControllerAdvice Global Error Handling Example in Spring Boot. Let’s see some points.

@ControllerAdvice Global Error Handling Example in Spring Boot

@ControllerAdvice – 

  • This annotation introduced in Spring 3.2 and available in org.springframework.web.bind.annotation package.
  • We are going to use @ControllerAdvice and @Exceptionhandler annotations in this example, @ControllerAdvice is used with class level for global error/exception handling in the Spring MVC application and @Exceptionhandler is used with methods(not with class).
  • We have a class called GlobalErrorHandling.java where we are going to use @ControllerAdvice and @Exceptionhandler annotations. We can configure multiple exceptions in this class so that in our application if that exception will occur, this class will get invoked and we will have a proper error message.

Step 1 – open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)click on next.

Step 2 –  Fill all details as below and click on finish.

 

@ControllerAdvice Global Error Handling Example in Spring Boot

Step 3 – Modify pom.xml

 

 

Directory structure –

 

Book.java

Story.java

BookController.java

StoryController.java

GlobalErrorHandler.java

 

RecordNotFoundException.java

ResponseError.java

SpringMain.java

application.properties

 

We are done. Let’s run and deploy the application.

@ControllerAdvice Global Error Handling

 

Request data to test BookController’s API – http://localhost:9093/book/test. We are intentionally providing bookId as null so that it will throw an exception and we will have error response.

@ControllerAdvice Global Error Handling

 

Request data to test StoryController’s API – http://localhost:9093/story/test

@ControllerAdvice Global Error Handling

 

In this example, we have seen how to handle exception/error globally. Suppose we are using our custom exception multiple places i.e we are throwing exception if reord is not there. In this case we will have error message “Record not found”. The same way we can define some other exception. We can also define NullPointerExcpetion or any other predefined exception as well as user-defined exception.

That’s all about @ControllerAdvice Global Error Handling Example in Spring Boot.

You may like –

 

Top