Search code examples
javaspring-mvcexceptionmodelandview

SimpleMappingExceptionResolver not Resolving 404


Below is my spring configuration file:

<bean class="com.web.handler.CustomSimpleMappingExceptionResolver" >
    <property name="exceptionMappings">
        <props>              
            <prop key="java.lang.Throwable">error</prop>
        </props>
    </property>
</bean>

Class CustomSimpleMappingExceptionResolver

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver{
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {

    if(int a = 1)
        return new ModelAndView("ViewName1");
    else
        return new ModelAndView("ViewName2");
    }

My web.xml has no error page. I am looking to show different view according to my logic in resolveException().

In CustomSimpleMappingExceptionResolver class resolveException() is not being called in case of 404.


Solution

  • Set error page in web.xml

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

    your error page will redirect as soon as it opened.

    <html>
        <head>
        <title>Your Page Title</title>
        <meta http-equiv="REFRESH" content="0;url=error.htm">
        </head>
        <body>
        </body>
    </html>
    

    There should be a request mapping in your controller to handle error.htm request.

    @RequestMapping(value={"/error.htm"})
        ModelAndView routToErrorHandler(HttpServletRequest request, HttpServletResponse response) {
    //any logic for your themes
    }