gpt4 book ai didi

Spring 启动 : how to log httpStatus 500 error

转载 作者:行者123 更新时间:2023-12-05 03:08:53 27 4
gpt4 key购买 nike

我创建了一个 AppErrorController,它扩展了 Boot 的 ErrorController 以处理 status500 错误。示例:

@Controller
public class AppErrorController implements ErrorController {
private static final Logger LOGGER = LogManager.getLogger(AppErrorController.class);
private static final String ERROR = "error";
private static final String ERROR_MESSAGE = "errorMessage";

@RequestMapping(value = "/error")
public String error(Exception e, Model model) {
LOGGER.error("500", e);
model.addAttribute(ERROR_MESSAGE, "Internal server error");
return ERROR;
}

@Override
public String getErrorPath() {
return ERROR;
}
}

我需要记录错误。但问题是 Exception e 总是 null。如何提取实际错误以便记录它?


已添加

我有一个 GlobalExceptionHandler,但它永远不会捕获“500”错误

@Component
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LogManager.getLogger(GlobalExceptionHandler.class);
private static final String ERROR = "error";

@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
LOGGER.error(e);
return ERROR;
}
}

最佳答案

从 jsp 层捕获异常的一种方法是定义您自己的 error-page 并将它的 location 指向您的 Controller 。然后您可以提取实际原因并根据需要进行处理。

web.xml

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error</location>
</error-page>

错误 Controller

@Controller
@RequestMapping("/error")
public class ErrorController {

private final Logger log = LoggerFactory.getLogger(ErrorController.class);

@RequestMapping
public String ex(HttpServletRequest request) {
Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
throwable.printStackTrace(); //print
log.error(throwable.getMessage(), throwable); // or log
// or save to db
return "error"; //and redirect to some user-friendly page
}
}

关于 Spring 启动 : how to log httpStatus 500 error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474752/

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