Spring Framework `@ExceptionHandler`
In Spring Framework, the `@ExceptionHandler` annotation is used to handle exceptions that occur during the execution of a controller method. This allows you to handle specific exceptions in a centralized manner without cluttering your code with `try-catch` blocks.
You can define exception handler methods in your controller or in a global exception handler class.
Example of using @ExceptionHandler:
Let’s look at an example of how to use the `@ExceptionHandler` annotation in a Spring Boot application:
Create a custom exception class First, let's define a custom exception that we will handle in the controller.
Create a custom exception class First, let's define a custom exception that we will handle in the controller.
Create a Controller that throws the exception
In this step, we’ll create a simple controller that throws a `ResourceNotFoundException` when an endpoint is accessed.
Handle the exception using `@ExceptionHandler`
Now, let’s handle the `ResourceNotFoundException` using the `@ExceptionHandler` annotation in the same controller.
For Explanation :
- @RestControllerAdvice: This is a specialized version of @ControllerAdvice that is used for global exception handling in @RestController methods. It allows you to handle exceptions across all controllers.
- @ExceptionHandler(ResourceNotFoundException.class): This annotation tells Spring that whenever a `ResourceNotFoundException` is thrown, the `handleResourceNotFoundException` method should handle it.
- ResponseEntity
: The method returns a ResponseEntity with a custom message and HTTP status code (404 in this case).
Running the Application When you run this Spring Boot application and access the /resource/{id} endpoint with an invalid ID (e.g., `/resource/0` or `/resource/-1`), it will return a response like:
HTTP Status: 404 Not Found Body: Resource with ID 0 not found!
Example Output:
- - When accessing `/resource/1`, it will return "Resource found with ID 1".
- - When accessing `/resource/0`, it will return a 404 response with the message "Resource with ID 0 not found!".
Advantages of using @ExceptionHandler:
Centralized exception handling. - Cleaner code with no need for `try-catch` blocks in each controller method.
Centralized exception handling. - Cleaner code with no need for `try-catch` blocks in each controller method.
Ability to return custom error responses with HTTP status codes.
You can handle multiple exceptions in a similar way by adding more `@ExceptionHandler`
methods in the same class, or even define exception handling globally for all controllers using `@ControllerAdvice` instead of `@RestControllerAdvice`.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment
Please Write a Message for Programming or something Related issues.