user1251534
user1251534

Reputation:

Exception Handling in Spring MVC 3 to Show a Custom Error Page for Invalid URL

I am using @ExceptionHandler in Spring mvc 3 application for exception handling and I have written a controller like this :

@Controller
public class ExceptionsController {

    private static final Logger logger = Logger.getLogger(ExceptionsController.class);


    @ExceptionHandler(IOException.class)
    public ModelAndView handleIOException(IOException ex) {

        logger.info("handleIOException - Catching: " + ex.getClass().getSimpleName());
        return errorModelAndView(ex);
    }


    private ModelAndView errorModelAndView(Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("name", ex.getClass().getSimpleName());

        return modelAndView;
    }

    @ExceptionHandler({NullPointerException.class, NoSuchRequestHandlingMethodException.class})
    public ModelAndView handleExceptionArray(Exception ex) {

        logger.info("handleExceptionArray - Catching: " + ex.getClass().getSimpleName());
        return errorModelAndView(ex);
    }


    @ExceptionHandler(DataFormatException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "My Response Status Change....!!")
    public ModelAndView handleDataFormatException(DataFormatException ex, HttpServletResponse response) {
        logger.info("Handlng DataFormatException - Catching: " + ex.getClass().getSimpleName());
        return errorModelAndView(ex);
    }

For this, I have configured spring servlet xml file with bean declaration of AnnotationMethodHandlerExceptionResolver

What I want is when a user modifies the URL, PageNotFound Exception should be handled by @ExceptionHandler.

My scenario is, in browser, when a user changes the URL manually that is not correct, in that case a 404 page is rendered by the server, in place of that I want to show an error page as it comes in Facebook

Upvotes: 1

Views: 5179

Answers (1)

Kevin Schmidt
Kevin Schmidt

Reputation: 2251

You don't need to use Spring for that. The 404 is created by your app server (e.g Tomcat). Depending on how your DispatcherServlet is set up, you can just add this to your web.xml to return a custom page:

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

Just make sure /error.html is either served by your app server (not by the DispatcherServlet) or as a pass-through from a file by Spring.

Upvotes: 4

Related Questions