membersound
membersound

Reputation: 86627

How to show custom error message for @ResponseStatus errors?

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

Answers (1)

user3247624
user3247624

Reputation: 70

Instead of using ResponseStatus. You can think of using ExceptionHandler.

@ExceptionHandler(Exception.class) public ModelAndView handleError(HttpServletRequest req, Exception ex) {..}

Upvotes: 1

Related Questions