我创建了一个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;
}
}
我需要记录错误。但问题是异常e总是为空。如何提取实际错误以便记录它?
ADDED
我有一个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;
}
}
答案 0 :(得分:2)
从jsp层捕获异常的一种方法是定义自己的error-page
并将其location
指向您的控制器。然后你可以提取实际的原因,并随心所欲地做。
的web.xml
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error</location>
</error-page>
ErrorController
@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
}
}