-
Couldn't load subscription status.
- Fork 38.8k
Description
I would like to back to issue that Tomcat servlet logs unhandled exceptions without trace/span id.
When unhandled exception reaches Tomcat servlet, standard log entry with level ERROR is logged.
I would like to customize the log message. Typical demand is trace/span id, let say I want to see also request path. Let's name it context.
It is sensible: when I see ERROR log entry, I would like to see collected all clues in one place
instead of start scan logs and collect myself.
What could I do:
- I could add
@ExceptionHandler void handleException(Exception ex, HttpServletResponse response) throws IOException {
log(context);
response.sendError(500);
}
Problem: Handler takes ResponseStatusException because ExceptionHandlerExceptionResolver
is before ResponseStatusExceptionResolver and does not honor ResponseStatusException code
1a. I could add dedicated implementation for ResponseStatusException
Problem: It does not have a sense to reimplement Spring code in custom code
1b. I could extend ResponseEntityExceptionHandler, part of Problem Details implementation.
The handler is facing similar problem and has dedicated implementation for ResponseStatusException
Problem: It adds Problem Details format for ResponseStatusException.
- I could implements
HandlerExceptionResolverwith
@Override public ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
try {
log(context);
response.sendError(500, ex.getMessage());
return new ModelAndView();
} catch (IOException e) {
return null;
}
}
It works.
Problem: Overloaded, unclerar, old-fashion API
Conclusion:
When Spring code catches unhandled exception, it should not buble it up to Tomcat Servlet. It is known that Tomcat Servlet will log meager error and pass to error controller with code 500.
It is typical expectancy that error log message is rich with plenty details.
For that reason I think that Spring log should:
- Log exception itself and call
response.sendRedirect()to make Tomcat NOT log the exception - Open API to easy customizing exception logging by developers.
However the expectancy can be satisfied with custom HandlerExceptionResolver, I think it should be more straightforward. Althought I'm very experienced with Spring MVC error handling, it took me few hours to invent solution (2).
I propose the following:
a) Add a dedicated, customizable HandlerExceptionResolver as last exception resolver in chain
b) Additionally ExceptionHandlerExceptionResolver should have same policy for standard Spring exceptions like ResponseEntityExceptionHandler
Of course I can't exclude there is much simpler solution 3...