0

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);
    }

3 Answers 3

3

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) {
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try using this instead. It's the deleteById method for a CrudRepository (hope you're using that) and it throws IllegalArgumentException if it can't find a customer.

I assumed that with "error" you meant "exception" and then in the controller you can surround with a try-catch block like that:

try{
    customerService.deleteCustomer(id);
} catch (IllegalArgumentException e) {
    log.error("No customer id exists!", e); 
    // if you have no logger, then use System.out.println() at least
}

If you wanted instead to return an error to the caller, then change the data type from void to HttpResponse<String> and when catching an exception you can return HttpResponse<>("No customer exists with that id!", HTTP.BAD_REQUEST). Now the caller will get a 400 - bad request.

A nicer approach would be to catch the exception in the service itself and return a boolean to the controller (true if customer is deleted and false if couldn't delete / couldn't find one).

2 Comments

That's a bad approach. It's worth checking id is not null to avoid IllegalArgumentException, so try-catch block is not recommended here.
That's what @NotNull is used for in the controller.
0

if you want to throw error then you will have to check a condition, that is there will be an if statement, but not necessarily an else is needed.

For instance, you can check response of delete and throw error according to below one.

if (deleteCount == 0) {
  //throw error here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.