Reputation: 86627
I created a custom @ResponseStatus
exception, and want it both being returned as a json response of a @RestController
, and also the response payload.
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends NestedRuntimeException {
public BadRequestException(String msg) {
super(msg);
}
}
I have a CommonsRequestLoggingFilter
that should log the response after it has been send. Therefore the filter reads wrapper.getContentAsByteArray()
:
public class CustomLoggingFilter extends CommonsRequestLoggingFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
ContentCachingResponseWrapper responseToUse = new ContentCachingResponseWrapper(response);
try {
super.doFilterInternal(request, responseToUse, filterChain);
} finally {
byte[] buf = responseToUse.getContentAsByteArray();
String message;
//PROBLEM: buf.length() == 0 in error case, thus cannot create the message
LOGGER.info("Response: " + message);
}
}
}
In general the loggings works, but in case of a @ResponseStatus
error, the response body/payload is lost!
Question: how can I keep the body payload for logging during an exception?
Upvotes: 3
Views: 1023
Reputation: 70
Instead of using ResponseStatus. You can think of using ExceptionHandler.
@ExceptionHandler(Exception.class) public ModelAndView handleError(HttpServletRequest req, Exception ex) {..}
Upvotes: 1