Spring Boot ControllerAdvice 如何抓取 Error 异常
Spring Boot About 1,948 words需求
需要捕获OutOfMemoryError
、StackOverflowError
等继承于Error
类的错误异常。
代码
对于抓取了Exception
级别的异常,都会走到这个ControllerAdvice
。
但发现在Controller
中模拟了OutOfMemoryError
,也会走到这个方法中。
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorInfo handleException(Exception ex, HttpServletRequest request) {
log.error("请求异常: {}", request.getRequestURI(), ex);
return new ErrorInfo();
}
原因
Spring
抓取了Throwable
级别的异常,并且再封装了NestedServletException
或者ServletException
,在这些异常的cause
中封装了Error
的错误信息。
public class DispatcherServlet extends FrameworkServlet {
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
// ...
try {
// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
// ...
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
// spring-webmvc-5.3.18
dispatchException = new NestedServletException("Handler dispatch failed", err);
// spring-webmvc-6.1.1
dispatchException = new ServletException("Handler dispatch failed: " + err, err);
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
// ...
}
}
兼容代码
使用ex.getCause()
获取异常的堆栈来判断即可。
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorInfo handleException(Exception ex, HttpServletRequest request) {
if (ex.getCause() instanceof Error) {
log.error("请求异常-Error: {}", request.getRequestURI(), ex);
} else {
log.error("请求异常-Exception: {}", request.getRequestURI(), ex);
}
return new ErrorInfo();
}
Views: 597 · Posted: 2024-04-03
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...