#how to properly handle case when theres no records in the db table?

31 messages · Page 1 of 1 (latest)

unborn swan
#

hey guys. so i have my CustomerRepo in my service and i want to handle a scenario when there are no customers with given id. so far i have this:

Optional<Customer> customer=customerRepository.findById(Long.valueOf(paymentInformationRequest.getClientId()));
        if (customer.isEmpty()) {
            log.info("BGWService.createPaymentInformation. no customer with id: {}", paymentInformationRequest.getClientId());
            throw new IllegalArgumentException("BGWService.createPaymentInformation. no customer with id:"+paymentInformationRequest.getClientId());
        }

but i was wondering if i can do smth better? thx

coral nightBOT
#

This post has been reserved for your question.

Hey @unborn swan! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

shy cave
#

use .orElseThrow on optional to throw an exception

#

Preferably an exception you define yourself that means that a customer isn't found

#

CustomerNotFoundException or something similar. This you can catch in a @ControllerAdvice

#

And then do the logging there

unborn swan
# shy cave `CustomerNotFoundException` or something similar. This you can catch in a @Contr...

u mean smth like this?

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value={IllegalArgumentException.class, IllegalStateException.class})
    protected ResponseEntity<Object> handleConflict(RuntimeException runtimeException, WebRequest webRequest) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(runtimeException, bodyOfResponse,new HttpHeaders(), HttpStatus.CONFLICT, webRequest);
    }
}
shy cave
#

It's been a while, I'd have to look all that up, but yeah, something along those lines

#

But don't do it for IllegalArgument or IllegalState

#

Make your own exceptions so you have a clear definition of what went wrong

unborn swan
#

i have :

@ControllerAdvice
@Slf4j
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value={IllegalArgumentException.class})

    protected ResponseEntity<Object> handleNoCustomerException(RuntimeException runtimeException, WebRequest webRequest) {
        //todo write custom exception when client doesnt exist

        log.info("BGWService.createPaymentpaymentConfirmation. NoCustomerException");

        String responseBody = "Customer with id"+;
        return handleExceptionInternal(runtimeException, responseBody,new HttpHeaders(), HttpStatus.CONFLICT, webRequest);
    }
}

and i have a question. how to pass argument to this contoller advice? can i pass it when throwing an exception?

shy cave
#

Yes, with a custom exception you can have as many arguments as you want

coral nightBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.

unborn swan
shy cave
#

That's up to you. There's merit in both

unborn swan
#

the more i read the less i understand

shy cave
#

Checked exceptions you have to either catch or declare explicitly (think IOException). Unchecked you don't (think IllegalArgumentException)

unborn swan
shy cave
#

That's the difference

unborn swan
#

?

shy cave
#

That's literally the difference between the two

#

Nothing more I can explain

#

You can ask a new question so other people can help. I'm sure plenty of people have opinions on when to use one or the other

unborn swan
#

then maybe you can explain how to pass arguments to my custom exception? i have this so far:

            throw new NoCustomerException("BGWService.createPaymentInformation. no customer with id:"+paymentInformationRequest.getClientId());

``` but idk how to pass arguments
shy cave
#

An exception is just a class, so you can add fields and constructor parameters

unborn swan
#

so i added another field:

public class NoCustomerException extends Exception {
    public NoCustomerException(String message, String clientId ) {
        super(message);
    }
}
#

an i use it like this:

 throw new NoCustomerException("BGWService.createPaymentInformation. no customer with id:"+paymentInformationRequest.getClientId(),paymentInformationRequest.getClientId());
#

but how to access the clientId here?

@ControllerAdvice
@Slf4j
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value={NoCustomerException.class})
    protected ResponseEntity<Object> handleNoCustomerException(RuntimeException runtimeException, WebRequest webRequest) {
        log.info("BGWService.createPaymentpaymentConfirmation. NoCustomerException");

        String responseBody = "Customer with id"+;
        return handleExceptionInternal(runtimeException, responseBody,new HttpHeaders(), HttpStatus.CONFLICT, webRequest);
    }

}
shy cave
#

Use the right exception as the parameter to that method