|
Answer» Below code STRUCTURE represent the ControllerAdvice class developed using spring boot framework to handle the exception. import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
// Need to mention the RestController so that it will behave as a controller class
@ControllerAdvice
public class ProductExceptionController {
// Below method USE to handle the exception, which is being generated by the RENT //endpoint method. This method also ACT as a User define exception.
@ExceptionHandler(value = ProductNotfoundException.class)
public ResponseEntity<Object> exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
}
}- Rest controller class which generate the exception
import java.util.HashMap;
import java.util.Map;
// Below SERIES of import is important package specially org.springframework package
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.demo.model.Product;
// This class represents how to call the exception handler class which is mention above.
@RestController
public class ProductServiceController {
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
// Below rest end points method throwing the exception if id is not found in databases, //so rather than call the runtime exception its calling the handler class, to catch the //exception and generate the appropriate message
@RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) {
if(!productRepo.containsKey(id))
throw new ProductNotfoundException();
productRepo.remove(id);
product.setId(id);
productRepo.put(id, product);
return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK);
}
}
|