0

I'm putting together a web app using Tomcat + Spring, and I'd like to have custom 404 pages which contain dynamic content, not just a static html file. For example, if I were working on a blog site, I might want to show a list of the 5 most recent posts on the 404 page to direct the user to actual content.

Additionally, is there a way I can leverage the error information when generating the error page? For example, if the error involved an exception happening in my app, as opposed to a bad url, can I display the stack trace?

Mar
  • 7,765
  • 9
  • 48
  • 82

1 Answers1

0

Are you creating the project from scratch? Are you able to use Spring-Boot? Spring Boot provides a lot of nice error handling functionality out of the box that can be easily modified.

Either way, if you just want to use standard error page mapping in the web.xml, or example:

<error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
</error-page>

When your application returns a 404 status code, the request will be intercepted and forwarded internally to the endpoint /error/404 - which can just be any endpoint in your spring app, so can do any dynamic stuff that you would in a normal controller.

To do it programatically, without Spring Boot, you could create a Filter class that wraps all requests and just catches exceptions and checks for non 2XX response codes and forwards/handles appropriately - this is basically the solution that the Spring Boot guys implemented (see the ErrorPageFilter class).

To access info about the exception, that can be accessed from the request - see here for similar answer: https://stackoverflow.com/a/1034667/258813

Community
  • 1
  • 1
rhinds
  • 9,976
  • 13
  • 68
  • 111