What exception should be made if the requested object does not exist in Db?

Imagine a method that tries to get an object that MUST exist in Db in terms of Business Logic (for a specific case).

When I try to extract it from Db through my repository, and if I return null , what exception should I throw? (I thought ObjectNotFoundException )

+7
source share
2 answers

It can be argued whether an exception is necessary at all; why not return an empty collection or null?

The type of exception you should use depends on how you use exceptions in the application.

The first thing you might think is whether it is a functional error (if the user has fixed something) or a technical error (the developers made a mistake).

Another thing you should consider is what is natural for the calling method.

+5
source

I would not throw an exception for such a scenario, just handle the null return value. It is not recommended that you start using exceptions to control application flow.

If the entity must be there, you can handle the null value in the business layer and throw a custom domain exception, for example. EntityNotFoundException , however, I would not put such logic at the repository level.

0
source

All Articles