Issue
I can’t understand how to handle the following error:
In the class CustomerService
I delete the customer by id
, and if such an id
does not exist, then an error must be thrown! How can you do without an if
else
construct?
CustomerService
:
// Delete customer
public void deleteCustomer(Long id){
Customer customer = customerRepository.getByIdAndUserRole(id, "customer");
customerRepository.delete(customer);
}
CustomerController
:
// DELETE MAPPING
//
// Delete customer with ID
@DeleteMapping("/customers/{id}")
void deleteCustomer(@PathVariable Long id) {
customerService.deleteCustomer(id);
}
Solution
Try to use Controller Advice. Whenever a exception occur it will directly handled by the handler. No if/else or try/catch blocks will be required.
1) Create a class CustomerControllerHandler, annotate with @ControllerAdvice.
2) Now create methods with arguments having the type of Exception.
3) The methods will return the JSON/POJO/void you want.
4) Annotate the methods with @ExceptionHandler(Exception.class) and @ResponseStatus(HttpStatus.BAD_REQUEST),
@ControllerAdvice
public class CustomerControllerHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void processException(Exception ex) {
}
}
Answered By - karan007