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

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());
}
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
20 Replies
JavaBot
JavaBot5mo ago
This post has been reserved for your question.
Hey @bambyzas! 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.
tjoener
tjoener5mo ago
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
bambyzas
bambyzasOP5mo ago
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);
}
}
@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);
}
}
tjoener
tjoener5mo ago
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
bambyzas
bambyzasOP5mo ago
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);
}
}
@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?
tjoener
tjoener5mo ago
Yes, with a custom exception you can have as many arguments as you want
JavaBot
JavaBot5mo ago
💤 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.
bambyzas
bambyzasOP5mo ago
but how do i know if i need checked or unchecked exception?
tjoener
tjoener5mo ago
That's up to you. There's merit in both
bambyzas
bambyzasOP5mo ago
but i dont even understand how they work and whats the difference the more i read the less i understand
tjoener
tjoener5mo ago
Checked exceptions you have to either catch or declare explicitly (think IOException). Unchecked you don't (think IllegalArgumentException)
bambyzas
bambyzasOP5mo ago
yes, i read that too, but it still doesnt explain a thing
tjoener
tjoener5mo ago
That's the difference
bambyzas
bambyzasOP5mo ago
?
tjoener
tjoener5mo ago
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
bambyzas
bambyzasOP5mo ago
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());
throw new NoCustomerException("BGWService.createPaymentInformation. no customer with id:"+paymentInformationRequest.getClientId());
but idk how to pass arguments
tjoener
tjoener5mo ago
An exception is just a class, so you can add fields and constructor parameters
bambyzas
bambyzasOP5mo ago
so i added another field:
public class NoCustomerException extends Exception {
public NoCustomerException(String message, String clientId ) {
super(message);
}
}
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());
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);
}

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

}
tjoener
tjoener5mo ago
Use the right exception as the parameter to that method
JavaBot
JavaBot5mo ago
💤 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.
Want results from more Discord servers?
Add your server