How to Create Global Exception Handler in Spring Boot
In Spring Boot, create a global exception handler by defining a class annotated with
@ControllerAdvice and methods annotated with @ExceptionHandler to catch and handle exceptions application-wide. This approach centralizes error handling and returns custom responses for different exceptions.Syntax
To create a global exception handler, use the @ControllerAdvice annotation on a class to make it a centralized exception handler. Inside this class, define methods annotated with @ExceptionHandler specifying the exception type to handle. These methods can return custom responses or views.
@ControllerAdvice: Marks the class as a global exception handler.@ExceptionHandler(ExceptionType.class): Handles specific exceptions.- Method parameters can include the exception object and
WebRequestfor request details. - Return type can be
ResponseEntityor any response object.
java
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllExceptions(Exception ex, WebRequest request) { return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
Example
This example shows a global exception handler that catches all exceptions and returns a JSON response with an error message and HTTP status 500. It demonstrates centralized error handling without repeating code in each controller.
java
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @RestController class TestController { @GetMapping("/error") public String throwError() { throw new RuntimeException("Something went wrong!"); } } @ControllerAdvice class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handleRuntimeException(RuntimeException ex, WebRequest request) { return new ResponseEntity<>("Custom error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
Output
HTTP/1.1 500 Internal Server Error
Content-Type: text/plain;charset=UTF-8
Custom error: Something went wrong!
Common Pitfalls
- Not annotating the handler class with
@ControllerAdvicewill prevent global handling. - Forgetting to specify the exception type in
@ExceptionHandlercauses the method not to be triggered. - Returning incorrect response types can cause client errors; use
ResponseEntityfor full control. - Defining multiple handlers for the same exception without clear priority can cause ambiguity.
java
/* Wrong: Missing @ControllerAdvice, so this handler won't work globally */ public class WrongHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handle(RuntimeException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } } /* Right: Add @ControllerAdvice to enable global handling */ import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class RightHandler { @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handle(RuntimeException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Error"); } }
Quick Reference
- @ControllerAdvice: Marks a class as a global exception handler.
- @ExceptionHandler(ExceptionType.class): Handles specific exceptions.
- ResponseEntity: Use to customize HTTP status and body.
- Define multiple methods for different exceptions.
- Use
WebRequestparameter to access request details if needed.
Key Takeaways
Use @ControllerAdvice to create a global exception handler class in Spring Boot.
Annotate methods with @ExceptionHandler specifying the exception type to handle.
Return ResponseEntity to customize HTTP status and response body.
Ensure the handler class is scanned by Spring by placing it in a component scan path.
Avoid missing annotations or wrong method signatures to ensure handlers work correctly.