gpt4 book ai didi

java - 如何在使用 ResponseStatusException 时记录异常信息

转载 作者:行者123 更新时间:2023-12-04 12:58:59 25 4
gpt4 key购买 nike

我同时使用 ExceptionAdviceResponseStatusException处理我的 Web 应用程序中的异常情况。现在我想在抛出 ResponseStatusException 时记录异常信息在我的 Controller 类中。

我总是可以在我的 Controller 类中抛出异常的行附近编写日志代码:

controllerMethod(){
logger.error("some thing happens here!");
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "some reason");
}

但是到处写代码太乏味了,事实上,我想要一些我在 ExceptionAdvice中使用的模式。类(class):

@ResponseBody
@ExceptionHandler(MyException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
String myExceptionHandler(MyException e){
logger.error("oops!", e);
return "something";
}

然而, ReponseStatusException Spring 生成的响应具有我想要维护的格式,例如:
{
"timestamp": "2018-02-01T04:28:32.917+0000",
"status": 400,
"error": "Bad Request",
"message": "Provide correct Actor Id",
"path": "/actor/8/BradPitt"
}

所以无论如何我可以使用建议类来记录 ResponseStatusException同时仍然保持其生成的响应,或者相反,使用其他类在所有 ReponseStatusException 周围添加日志能力无需输入 logger.error到处抛出异常?

最佳答案

这是一种方法(在 Spring Boot 2.3.3 中测试)。
创建一个扩展 ResponseStatusExceptionResolver 的类:

    /**
* Extended implementation that adds logging of {@link ResponseStatusException}s.
* <p>
* Note: {@link #setMessageSource(MessageSource)} has to be called if reason is a message code, rather than a message itself
*/
private static class LoggingResponseStatusExceptionResolver extends ResponseStatusExceptionResolver {
@Override
protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log(responseStatus.code(), responseStatus.reason(), ex);
return super.resolveResponseStatus(responseStatus, request, response, handler, ex);
}

@Override
protected ModelAndView resolveResponseStatusException(ResponseStatusException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log(ex.getStatus(), ex.getReason(), ex);
return super.resolveResponseStatusException(ex, request, response, handler);
}

private void log(HttpStatus status, String reason, Exception exception) {
if (status.isError()) {
logger.error(status + ": " + reason + "\n", exception);
}
}
}
然后在您的应用程序配置类之一中实现 WebMvcConfigurer并用扩展的替换默认解析器:
    @Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.replaceAll(resolver ->
resolver instanceof ResponseStatusExceptionResolver
? new LoggingResponseStatusExceptionResolver()
: resolver
);
}

关于java - 如何在使用 ResponseStatusException 时记录异常信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61952631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com