开发者

Catch Spring MVC No Mapping Error

开发者 https://www.devze.com 2023-01-17 22:32 出处:网络
I configured below exception resolver in my web configuration file but I am not sure why it cannot handle

I configured below exception resolver in my web configuration file but I am not sure why it cannot handle errors such as this 'No Matching error found for servlet request: path '/etc'

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings开发者_如何学JAVA">
        <props>
            <prop key="java.lang.Exception">
                exception
            </prop>
        </props>
    </property>
</bean>

My app relies on Ajax and there are cases that I change the target url based on some user interactions.

My question is, is it possible for me to catch the error in my Spring MVC and forward it to my exception.jsp so that my user wont get a nasty 404.


SimpleMappingExceptionResolver (and the HandlerExceptionResolver framework in general) will only be invoked to handle exceptions generated by the request handler (i.e. your controllers). If no handler is configured to handle the request, then it won't get that far, and your resolver won't be invoked.

The simplest thing for you to do is to configure a 404-handling page in your web.xml, e.g.

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


You could set up a catch-all @RequestMapping and throw a custom exception if it is executed. Then you could handle that exception with the SimpleMappingExceptionResolver or an @ExceptionHandler method (maybe in a @ControllerAdvice class).

The catch-all controller:

@RequestMapping(value = "/**")
public ModelAndView noHandlerMappingFound() throws HandlerNotFoundException {
    throw new HandlerNotFoundException("No handler mapping found.");
}

Here HandlerNotFoundException is your custom exception type.

The controller advice:

@ExceptionHandler(NoSuchEntityException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleNoSuchEntityException(final HttpServletRequest req, final Exception ex) {
    return new ModelAndView("error-page");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消