mjs
mjs

Reputation: 22369

Spring, showing an error occurred view on exception or 404

I have

@Controller
@RequestMapping(value="core/*")
public class CoreController {

    public static String exceptionOccurredView = "/core/exceptionOccurred";

    @ExceptionHandler(Throwable.class)
    public ModelAndView exceptionOccurred(Throwable exception, HttpServletResponse response, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName ( exceptionOccurredView );
        mv.addObject   ( "requestedUrl", Core.getCurrentUrlWithParams() );
        mv.addObject   ( "exception", exception );

        System.out.println( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + Core.getCurrentUrlWithParams() );
        return mv;
    }   

    @RequestMapping
    public void test0(HttpServletResponse response, HttpServletRequest request) throws IOException {
        throw new IOException();
    } 

}

which works fine for all exeptions occuring under core url.

if I go to url

localhost:8080/core/test0

the error page is shown. Also if I go to:

localhost:8080/core/actionDoesNotExist

but if I use:

localhost:8080/controllerDoesNotExist/test0

The error does not get shown, since the annotation @ExceptionHandler is valid only per controller.

So how can you achieve a global, non-controller attached exception/error handler ?

Upvotes: 0

Views: 1171

Answers (1)

soulcheck
soulcheck

Reputation: 36767

One way would be to use some implementation of HandlerExceptionResolver.

For example to use `SimpleMappingExceptionResolver, put this in your context:

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
      <map>
         <entry key="IOException" value="io-error" />
      </map>
    </property>
    <property name="defaultErrorView" value="default-error"/>
</bean>

That way you define a global mapping from exceptions to error pages. If you need some more complicated error handling, implement your own resolver.

Upvotes: 1

Related Questions