Spring MVC: Beginner's Guide - Second Edition by Amuthan Ganeshan

Spring MVC: Beginner's Guide - Second Edition by Amuthan Ganeshan

Author:Amuthan Ganeshan [Ganeshan, Amuthan]
Language: eng
Format: azw3
Publisher: Packt Publishing
Published: 2016-07-29T04:00:00+00:00


Now run our application and enter http://localhost:8080/webstore/market/product?id=P1000. You will see an error page showing There is no product found with the Product id P1000 as follows:

Product detail page showing a custom error page for the product ID P1000

What just happened?

We decided to show a custom-made error page instead of showing the raw exception in the case of a product not being found for a given product ID. So, in order to achieve that, in step 1 we just created a runtime exception called ProductNotFoundException to be thrown when the product is not found for the given product ID.

In step 2, we just modified the getProductById method of the InMemoryProductRepository class to check whether any products were found for the given product ID. If not, we simply throw the exception (ProductNotFoundException) we created in step 1.

In step 3, we added our exception handler method to handle ProductNotFoundException with the help of the @ExceptionHandler annotation. Within the handleError method, we just created a ModelAndView (org.springframework.web.servlet.ModelAndView) object and stored the requested invalid product ID, exception, and the requested URL, and returned it with the View name productNotFound:

@ExceptionHandler(ProductNotFoundException.class) public ModelAndView handleError(HttpServletRequest req, ProductNotFoundException exception) { ModelAndView mav = new ModelAndView(); mav.addObject("invalidProductId", exception.getProductId()); mav.addObject("exception", exception); mav.addObject("url", req.getRequestURL()+"?"+req.getQueryString()); mav.setViewName("productNotFound"); return mav; }

Since we returned the ModelAndView object with the View name productNotFound, we must have a View file with the name productNotFound. That's why we created this View file (productNotFound.jsp) in step 4. productNotFound.jsp just contains a CSS-styled <h1> tag to show the error message and a link button to the product listing page.

So, whenever we request to show a product with an invalid ID such as http://localhost:8080/webstore/product?id=P1000, the ProductController class will throw the ProductNotFoundException, which will be handled by the handleError method and will show the custom error page (productNotFound.jsp).



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.