Controller Advice

Learn via video courses
Topics Covered

Overview

Every software program can run into an error that developers must handle cautiously. Handling exception is an important part of building resilient and robust applications.

Introduction to Spring Boot Controller Advice

Spring provides a useful way to handle the API exception using controller advises, which can handle all the exceptions thrown by controller classes. Controller advice leverages the aspect-oriented programming principle. Therefore exceptions can be handled using cross-cutting concerns.

Advantages of Controller Advice

  • Controller advises working as a global exception handler for all API exceptions.
  • Controller advice helps keep the controller code clean and declutter from error-related code.
  • One controller advice can be applied to all the controllers in the system.
  • Eliminates exception logic duplication among multiple controller classes.

How does @ControllerAdvice work?

@ControllerAdvice is a specialized form of the spring's stereotype annotation which allows handling exceptions across the whole application in one global handling component.

controller-advice-working

Think of this as an interceptor of exceptions thrown by methods annotated with @RequestMapping.

Controller advice uses AOP @AfterThrowing advice to handle the exception as a cross-cutting concern.

Spring Boot Exception Handling Using Controller Advice

Let's code a simple use case with controller advice. We have an employee management system. It contains an API to fetch an employee by ID. Employee Service throws the exception EmployeeNotFoundException if an employee is not found.

EmployeeService

Employee Controller

Invoking API now will return the below response:

By default, spring converts exceptions to an internal server error. Having a "500- Internal server error" response for all the errors in the system does not go with the style of the HTTP and REST. We should deal with exceptions as per the standard of HTTP and REST.

Create Controller Advice with @ExceptionHandler

Our case response should be returned "404 - Not found" because the resource user trying to fetch does not exist. Now we will apply controler advice and verify the response again.

Applied @ControllerAdvice.handleEmployeeNotFound can intercept exceptions from controllers across the application, which throws EmployeeNotFoundException.

@ResponseStatus

Spring provides a useful annotation @ResponseStatus to change the response with the correct HTTP Status code. In our advice, we are dealing with the exception and returning @ResponseStatus(HttpStatus.NOT_FOUND), which is better suited for our use case.

Create Custom Exception

Despite Spring providing many classes representing common exceptions in an application, it is better to practice writing your own or extending existing ones.

Define Error Response Message

Spring boot allows us to customize the error response if we don't want to use the default spring boot response.

Custom API Response

Controller Advice

Now we are returning ExceptionResponse instead of ResponseEntity.

Run and Test

Let's run the application and test it.

  • Case 1 - Advice returning ResponseEntity. When we invoke the endpoint http://localhost:8080/employee/1, it returns the response below:
  • Case 2 - Custom API Response- ExceptionResponse Hitting endpoint now should return below response with HTTP status 404:

Spring Boot is revolutionizing Java development. Enroll in our free Spring Boot online course and learn to create microservices and web applications with ease.

Conclusion

  • Spring boot framework provides an efficient way to deal with API exceptions using @ControllerAdvice.
  • Controller advice act as an interceptor to methods annotated with @RequestMapping.
  • One piece of advice can cut through all the controllers in the system.
  • One @ExceptionHandler can deal with multiple exceptions.
  • Controller advice helps API method code clean by separating error-related handling from the positive response.