Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check for Spring6 specific servlet attribute for advice-handled exception #1538

Merged
merged 1 commit into from
Oct 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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));
}
}
Loading