我创建了一个自定义的@ResponseStatus异常,并希望将其作为@RestController的json响应以及响应有效负载返回。

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends NestedRuntimeException {
    public BadRequestException(String msg) {
        super(msg);
    }
}

我有一个CommonsRequestLoggingFilter,应该在发送响应后记录响应。因此,过滤器读取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);
        }
    }
}

通常,日志记录是可行的,但是如果出现@ResponseStatus错误,响应主体/有效负载将丢失!

问题:如何在异常期间保留主体有效载荷以进行记录?

最佳答案

而不是使用ResponseStatus。您可以考虑使用ExceptionHandler。

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

10-06 13:53