From 7057e595e394912ead7a993849f634fa685246b2 Mon Sep 17 00:00:00 2001 From: Jerry Duffy Date: Thu, 5 Oct 2023 11:42:43 -0400 Subject: [PATCH] Check for Spring6 specific servlet attribute for advice-handled exception --- .../tomcat10/TomcatServletRequestListener.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/instrumentation/tomcat-10/src/main/java/com/nr/agent/instrumentation/tomcat10/TomcatServletRequestListener.java b/instrumentation/tomcat-10/src/main/java/com/nr/agent/instrumentation/tomcat10/TomcatServletRequestListener.java index a6073590ec..35fb47a70e 100644 --- a/instrumentation/tomcat-10/src/main/java/com/nr/agent/instrumentation/tomcat10/TomcatServletRequestListener.java +++ b/instrumentation/tomcat-10/src/main/java/com/nr/agent/instrumentation/tomcat10/TomcatServletRequestListener.java @@ -21,7 +21,8 @@ public final class TomcatServletRequestListener implements ServletRequestListener { - private static final String EXCEPTION_ATTRIBUTE_NAME = "jakarta.servlet.error.exception"; + private static final String SERVLET_EXCEPTION_ATTRIBUTE_NAME = "jakarta.servlet.error.exception"; + private static final String SPRING6_SERVLET_EXCEPTION_ATTRIBUTE_NAME = "org.springframework.web.servlet.DispatcherServlet.EXCEPTION"; private static final String REQUEST_FIELD = "request"; private final Field requestField; @@ -44,8 +45,7 @@ private Field getRequestField() { @CatchAndLog @Override public void requestDestroyed(ServletRequestEvent sre) { - - Throwable exception = (Throwable) sre.getServletRequest().getAttribute(EXCEPTION_ATTRIBUTE_NAME); + Throwable exception = retrieveExceptionFromServlet(sre); if (exception != null) { AgentBridge.privateApi.reportException(exception); } @@ -98,4 +98,12 @@ private Request_Weaved getRequest(HttpServletRequest httpServletRequest) { } return null; } + + private Throwable retrieveExceptionFromServlet(ServletRequestEvent sre) { + //As of Spring 6, when controller advice is used for controller exception handling, the caught exception is + //now stored in the servlet attribute map with the "org.springframework.web.servlet.DispatcherServlet.EXCEPTION" key. + return (Throwable) (sre.getServletRequest().getAttribute(SERVLET_EXCEPTION_ATTRIBUTE_NAME) != null ? + sre.getServletRequest().getAttribute(SERVLET_EXCEPTION_ATTRIBUTE_NAME) : + sre.getServletRequest().getAttribute(SPRING6_SERVLET_EXCEPTION_ATTRIBUTE_NAME)); + } } \ No newline at end of file