0

With Spring 5, I am currently able to configure an error page in src/main/webapp/web.xml, i.e. the following configuration is added:

<error-page>
    <location>/WEB-INF/error.html</location>
</error-page>

In this way, the error.html will be rendered when there is Exception in the controller. However, this error.html is in html format other than the expected JSON format.

I tried to make an error controller with some code like this:

    @RestController
    @RequestMapping(value = "/handler")
    public class ErrorController {

      @RequestMapping(value = "/errors")
      public String renderErrorPage(HttpServletRequest httpRequest) {
        System.out.println("DEBUG::come to error page");
        return "test error";
      }
    }

In the same time configured error-page as such:

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<error-page>
    <location>/handler/errors</location>
</error-page>

But the ErrorController cannot be invoked.

Question: How to configure Spring error page in JSON format with web.xml and an error controller?

Cedric Druck
  • 1,032
  • 7
  • 20
Rui
  • 3,454
  • 6
  • 37
  • 70

1 Answers1

0

I eventually realized that the servlats are filtered with /rest/* through the servlet-mapping tag, so the location of the error-page has to be prefixed with /rest, meaning the error-page tag should be configured as such:

<error-page>
    <location>/rest/errors</location>
</error-page>

Correspondingly the controller can be configured like:

@RestController
//@RequestMapping(value = "/handler")
public class ErrorController {

    @RequestMapping(value = "/errors")
    public String renderErrorPage(HttpServletRequest httpRequest) {
        System.out.println("DEBUG::come to error page");
        return "test error";
    }
}
Rui
  • 3,454
  • 6
  • 37
  • 70