Search code examples
tapestry

Custom application exception HTTP status code


I've used the #3 method from this page to customize the application exception page when in production mode, however my error page returns 200OK HTTP status code while I want it to return 500 Internal Server Error (as it is in development environment).

I am not sure how to change the status code. Any ideas?


Solution

  • In the handleRequestException implementation of the DefaultRequestExceptionHandler which is used by default, you can see that the response status is set to 500:

    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    

    You would have to do something very similar in your code (not tested):

    public RequestExceptionHandler decorateRequestExceptionHandler(final Logger logger, final ResponseRenderer renderer,
        final ComponentSource componentSource, final Response response,
        @Symbol(SymbolConstants.PRODUCTION_MODE) boolean productionMode, Object service) {
        if (!productionMode) return null;
    
        return new RequestExceptionHandler() {
            public void handleRequestException(Throwable exception) throws IOException {
                logger.error("Unexpected runtime exception: " + exception.getMessage(), exception);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                ExceptionReporter index = (ExceptionReporter) componentSource.getPage("Index");
    
                index.reportException(exception);
    
                renderer.renderPageMarkupResponse("Index");
            }
        };
    }