Reputation: 5577
I am trying to handle Exceptions that are thrown by JSP views. As Spring MVC cannot handle these exceptions directly, because they are thrown out of scope of the controllers, I tried to handle them via an HandlerInterceptorAdapter
.
The afterCompletion
method gives me access to the Exception thrown from a JSP, so I can log the exception with a unique error id. But in addition I want to display a user friendly error page to the customer. So my first thought was to redirect the user to my already existing error page, which shows the unique error id.
But it seems that the redirect is ignored. Is it possible at all to do a redirect in this method? Or isn't it possible to change the response, because it is already rendered?
Here is my first try:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import de.lwv.mass2.client.web.controller.BasicExceptionHandlerController;
@Component
public class JspExceptionHandler extends HandlerInterceptorAdapter {
private static Logger LOGGER = LoggerFactory.getLogger(JspExceptionHandler.class);
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if (ex != null) {
final String uuid = BasicExceptionHandlerController.generateExceptionUUID();
LOGGER.error("Exception: " + uuid, ex);
// redirect
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.sendRedirect(request.getContextPath() + "/error?id=" + uuid);
}
}
}
Upvotes: 1
Views: 1764
Reputation: 23014
I think the response has already been committed (and the view rendered) when afterCompletion
is called.
As an alternative suggestion, you could add an error-page
to your web.xml
which would act as a 'catch all' handler - catching exceptions originating from JSP views and other exceptions that couldn't be handled by the HanlderInterceptorAdapter
For example, in your web.xml you can add:
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error</location>
</error-page>
You can also define these by error code:
<error-page>
<error-code>500</error-code>
<location>/error</location>
</error-page>
The <location>
can be another controller, a static HTML page, or a JSP view - such as below.
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/jsp/500.jsp</location>
</error-page>
Upvotes: 1