I am using both the ExceptionAdvice
and ResponseStatusException
to handle the exception situation in my web application. Now I'd like to log the exception information while throwing the ResponseStatusException
in my Controller class.
I can always write the log code near the line that throw the exception in my Controller class:
controllerMethod(){
logger.error("some thing happens here!");
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "some reason");
}
But writing code all over the place is too tedious, In fact, i'd like some pattern that i used in my ExceptionAdvice
class:
@ResponseBody
@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
String myExceptionHandler(MyException e){
logger.error("oops!", e);
return "something";
}
However, the ReponseStatusException
response that Spring generated has the format which i want to maintain like:
{
"timestamp": "2018-02-01T04:28:32.917+0000",
"status": 400,
"error": "Bad Request",
"message": "Provide correct Actor Id",
"path": "/actor/8/BradPitt"
}
So is there anyway that i can use advice class to log for the ResponseStatusException
while still maintaining its generated response, or, on the contrast, using other class to add log ability around all the ReponseStatusException
without typing the logger.error
everywhere that the exception is thrown?
The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown.
The exception log is a rolling collection of 4 files; when a file is full, data is added to the next file. When the last file has been filled, data starts to be added to the first file, overwriting the previous data there. This cycle of writing continues, ensuring that the newest data is retained.
You have to provide implementation to use your error handler, map the response to response entity and throw the exception. Create new error exception class with ResponseEntity field. Custom error handler which maps the error response back to ResponseEntity.
Published: 13 Apr 2022. Logging and exception handling are like two peas in a pod. When a problem happens in your Java code, that typically means you have an exception that needs to be handled, and of course, any time an error or unanticipated event occurs, that occurrence should be logged appropriately.
You can enable the logging with the property
spring.mvc.log-resolved-exception=true
involved classes are
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With