Time for action – adding an exception handler
We must show a nice error message that says that no products were found with the given product ID. Let's do that with the help of @ExceptionHandler
:
- Create a class called
ProductNotFoundException
under thecom.packt.webstore.exception
package in the source foldersrc/main/java
. Now, add the following code to it:package com.packt.webstore.exception; public class ProductNotFoundException extends RuntimeException{ private static final long serialVersionUID =-694354952032299587L; private String productId; public ProductNotFoundException(String productId) { this.productId = productId; } public String getProductId() { return productId; } }
- Now, open our
InMemoryProductRepository
class and modify thegetProductById ...
Get Spring MVC Beginner’s Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.