Spring Boot ControllerAdvice 如何抓取 Error 异常

Spring Boot About 1,948 words

需求

需要捕获OutOfMemoryErrorStackOverflowError等继承于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: 159 · Posted: 2024-04-03

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh