Search code examples
javaexceptionspring-bootspring-restcontroller

Using exception for communication


I have heard that one should not use exception for communication. I have a scenario that I would like to discuss. We have a rest controller that invokes a service that is responsible for fetching a product from the database. Currently if product can't be found we will get an exception (checked exception) productNotFoundException. This exception goes all the way to the controller. In the controller we have a controller exception handler (controller advice) that takes care of the exceptions and returns 404.

I was told that if they are run on different threads then the whole application would crash and it would be better to deal with the exception directly. Currently a lot of methods are being called and all have throws prodNotfoundex.

Can some one explain why it would crash. My project is a spring boot project.

I was told to return an empty response to the controller instead of throwing an exception.


Solution

  • I'm not sure how it would crash your application, if you handle/catch the exception properly.

    Regarding exceptions, it should be seen as an exceptional state -- that is not in the normal flow of actions. Eg. the FileNotFoundException is exceptional, because you wanted to open the file, but it's not there. You expected it to be there, but it wasn't.

    If you search for a product, you don't expect it to be there in the general sense of "expecting to find a loaf in the grocery store". You searched for a bunch of keywords, and the search resulted an empty response/zero matches. It is not exceptional in your business logic.

    On the other hand, when you click "order" on a product (say on the product page), and then the product is not found, it is "exceptional". You expected a product you found 2 minutes ago to be there, but it isn't any more.

    Some links on Java Exception handling costs:

    Decide it for yourself.