I am sure this is one of those topics with no definite answers but how do you all think about throwing exceptions in kotlin while working with spring?
Roman Elizov has a great blog post on how to use exceptions with Kotlin. He emphasizes that catching exceptions in kotlin is usually code smell.
But does that mean that I should be able to throw exceptions freely in my Spring application if I am using application level exception handlers? More specifically let's say I have function that looks up an item in the database, and a controller that calls this service. If the item is not in the database, should I return a nullable from the service or should I throw an exception?
07/20/2022, 3:23 AM
I don’t know much about Spring Boot, but there are some top-of-the-line exception handling solutions in Kotlin that use
monad comprehension. There was a recent video from JetBrains about this in the context of a Ktor application here:
07/20/2022, 5:12 AM
And shameless promotion about error handling from my end ))
(also contains a spring boot like example)
In a way it doesn't matter that much. You can use Kotlins nullability system, the Result type, a sealed class or arrows Either. Usually I would runtime exceptions should be for unrecoverable errors in all contexts (just crash the program). All the other options are basically there to give the caller an option to either recover or crash. (Which is good, since some contexts might be able to recover, while others can't). They also add honesty to the function signatures, since they now clearly show they can fail. These are things however that add correctness to code. The more complex your application is, the more correctness you want. On the other hand.. if it's only a simple crud application, it matters less