我创建了一个自定义@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
错误,则响应正文/有效负载会丢失!
问题:如何在异常期间保留身体有效负载以进行记录?
答案 0 :(得分:1)
而不是使用ResponseStatus。您可以考虑使用ExceptionHandler。
@ExceptionHandler(Exception.class) public ModelAndView handleError(HttpServletRequest req,Exception ex){..}