Richard D
Richard D

Reputation: 133

when to catch exception, early or later?

I have a question about catching exception. I have different layers at back-end, such as repository, data-processing, controller three layers. I am wondering if there is a exception thrown at repository layer, should I catch it at repository layer or catch it at controller layer or even routing layer on top of controller. Someone suggested catch all exceptions at one layer, look like it simplifies the processing. But I heard from other guys that it is better to catch the exceptions early.

Please leave your opinions. Thanks a lot.

Upvotes: 0

Views: 341

Answers (1)

David
David

Reputation: 218827

Generally you would catch an exception wherever you can meaningfully do something with it. Whether you can meaningfully handle it and continue with the application, or whether you want to just log it and re-throw, or perhaps add information to it and re-throw, etc.

Someone suggested catch all exceptions at one layer

There is no one single place which will always be able to meaningfully handle all possible errors. As an example, consider a scenario in which a user uploads a spreadsheet of records to be batch processed in some way. Each record needs to be processed individually, and the system simply loops through them. What should happen if one of the records fails with an exception?

That depends on what the needs of the system are. Consider two different requirements:

  • If a single record fails, store somewhere that it failed but continue to process the rest of the records. After the batch completes, send the user a report of failed records.

Or:

  • If a single record fails, roll back the entire batch and notify the user that the batch was corrupted and indicate which record caused the problem.

In one of those scenarios it would make sense to catch and handle the exception within the loop and not let control flow leave that loop. In the other scenario it would make sense to catch the exception at the level of a unit of work wrapping the entire process, and to commit or rollback the entire operation accordingly. These could be vastly different parts/layers in the code.


If there's something you can or should do with an exception at a certain part of the code, catch the exception and perform that task. If there isn't, let the exception continue up the stack until it reaches something that can respond to it in some way.

In many cases (but certainly not as a universal rule for all cases) you generally want a global top-level exception handler just to prevent the application itself from failing. Ideally most exceptions would never reach that top-level handler, as it's basically a catch-all indicating that something unexpected failed and none of the code within the application was able to meaningfully handle that failure.

Upvotes: 2

Related Questions