hey there! how do you treat information not found...
# spring
t
hey there! how do you treat information not found in Kotlin? I’m doing
this.repository.findByIdOrNull
and when programming in Java I throw a Custom Exception (
ResourceNotFoundException
for example). What is a best practice to do this in Kotlin?
d
You could use the elvis operator for that. See https://kotlinlang.org/docs/reference/null-safety.html - for example:
Copy code
val name = node.getName() ?: throw IllegalArgumentException("name expected")
t
Ok. I asked because since kotlin doesn’t have the checked exceptions I was thinking if there was another way to handle this situation
j
Why would method named findByIdOrNull throw exception if item is not found? Shouldn't it return nullable value in that case because of method name? Or whats OrNull here exactly?
In any case what would you do if you had checked exceptions? You can do same handling for nullable value. Or if it's actually an error throw exception and dont use nullable
t
I didn’t express myself well. Actually it’s a method in service layer calling
this.repository.findByIdOrNull
and in case receive null throws an Exception
ResourceNotFoundException
to the controller layer
m
First question. Is not finding a record truly an exceptional situation or merely missing data? i.e. what does the caller of this service do with the exception? If they have branching logic, then it should just return the null in Kotlin (and I would have returned an Optional in Java). If the caller lets the exception ‘bubble up’, then there’s no reason you can’t throw an exception in Kotlin too. The only difference is Kotlin doesn’t force the caller to handle an exception if it’s checked. Code can catch an exception, but doesn’t HAVE TO if it’s checked. I am merely asking the same thing as @Jukka Siivonen.
👍🏻 1
v
it depends on what the service layer method does and if a value not found is fatal or not. For example when resetting a password and the user or resetCode is not found I typically do this by throwing a
ResourceNotFoundException
in the service layer by using the elvis operator after
findByIdOrNull()
, the exception is handled by a
@ControllerAdvice
class. If the absence of a value is not fatal I will just return the nullable value to the controller and have the controller handle the presence/absence check.
👍🏻 1