Question

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.

Was it helpful?

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
}

OTHER TIPS

The declaration might be incorrect; use a map instead of properties.

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
  <map>
    <entry key="DataAccessException" value="data-error" />
    <entry key="com.stuff.MyAppRuntimeException" value="app-unchecked-error" />
    <entry key="com.stuff.MyAppCheckedException" value="app-checked-error" />
  </map>
</property>
<property name="defaultErrorView" value="general-error"/>
</bean>

Also, I'm not sure SimpleMappingExceptionResolver handles errors thrown when finding a handler but rather it handles errors thrown from inside handlers. That said, I'm not sure 404 can caught this way.

If you put a error handler in web.xml that will go back into your servlet where you can handle it any way you like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top