To make method mark with @ExceptionHandler
Accepts parameters to help with the exception handling and provide response.
Sample Exception handler
- use the annotation
- pass the exception that this exception hanlder function handles as an argument
- below is handled for indexoutofboundexception
If we add this in controller: Then this will become global exception for that controller class
Can add @ResponseStatus to return desired HTTP Error code
Now when Controller gets this exception, it also return "Oops, something went wrong@ along with HTTP Error Code 400 as provided with @ResponseStatus above
Topic 3:
Controller can have multiple exception handler to handle different exceptions.
One is to add all exceptions as below, which is not practically possible in many cases
OR make indepeent handler so that we can customize the error code
Topic 4)
To embed some content from request recived in response while handling exceptions, we can use HttpServletRequet and Exception e value can be used to log to know about the exception
FAQ :
Q) Can I use ExceptionHandler annotation in any class?
Ans:
The @ExceptionHandler
annotation is used in Spring Framework to define a method that handles exceptions thrown by a controller method.
In order to use the @ExceptionHandler
annotation, the method that handles the exception should be defined within a class annotated with @ControllerAdvice
or @RestControllerAdvice
. These annotations allow the class to handle exceptions across multiple controller classes.
So, the answer is no, you cannot use the @ExceptionHandler
annotation in any class. It should only be used within a class annotated with @ControllerAdvice
or @RestControllerAdvice
.
No comments:
Post a Comment