Skip to content

Commit

Permalink
Merge pull request #1538 from newrelic/1393-controller-advice-errors
Browse files Browse the repository at this point in the history
Check for Spring6 specific servlet attribute for advice-handled exception
  • Loading branch information
jtduffy authored Oct 9, 2023
2 parents acdee64 + 7057e59 commit 1b9bd7f
Showing 1 changed file with 11 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
}
Expand Down Expand Up @@ -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));
}
}

0 comments on commit 1b9bd7f

Please sign in to comment.