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:
but i was wondering if i can do smth better? thx
20 Replies
⌛
This post has been reserved for your question.
Hey @bambyzas! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose 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.
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 thereu mean smth like this?
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
i have :
and i have a question. how to pass argument to this contoller advice? can i pass it when throwing an exception?
Yes, with a custom exception you can have as many arguments as you want
💤
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.
but how do i know if i need checked or unchecked exception?
That's up to you. There's merit in both
but i dont even understand how they work and whats the difference
the more i read the less i understand
Checked exceptions you have to either catch or declare explicitly (think IOException). Unchecked you don't (think IllegalArgumentException)
yes, i read that too, but it still doesnt explain a thing
That's the difference
?
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
then maybe you can explain how to pass arguments to my custom exception? i have this so far:
but idk how to pass arguments
An exception is just a class, so you can add fields and constructor parameters
so i added another field:
an i use it like this:
but how to access the clientId here?
Use the right exception as the parameter to that method
💤
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.