Madhur Maurya
Madhur Maurya

Reputation: 1070

Handle exception across multiple layers in a project

I am looking for a design pattern that will provide me a good mechanism to handle the exceptions thrown across the multiple layers of a project. Looking for some good design pattern that fits in the situation. I am working in .net environment. Thanks in advance.

Upvotes: 0

Views: 2217

Answers (2)

Andrea Rega
Andrea Rega

Reputation: 371

I think that the focus point is for how many purposes you are going to use the exceptions. In example:

  1. Business rules validation - if a business rule fail then you raise an exception;
  2. Runtime exception - connection lost/refused, etc..
  3. Frontend validation errors - the user data or the user workflow is not compliant with some requirements and so on...
  4. Fatal errors - errors with a severity very high that must break the application workflow (reference to null object...)

given these simple scenarios you can understand if your exception must be handled by the layer in which it has been raised or if it takes to make it "bubble" towards to user.

The case (1) for example could be managed by defining a common ValidationErrorHandler that will map each single exception into a log message/(re)action/validationReportObject and so on... and then returning to the user (or the caller) a describing object

The case (3) and (4) could be managed both inside the raising layer or propagated to the higher layer. It depends on how much knowledge about "how things works" you want to give to the end user.

The case (3) has not real exceptions but this is the case in which you could map directly the exception/error with a message to the user without involving other layers.

I hope this could help you. Maybe if you give us more informations about your use cases we can find a better and deeper soluion

Upvotes: 1

Harry
Harry

Reputation: 5707

I assume you are using n-tier architecture.
As you probably know, every architecture has its own pros & cons. And exception handling is one of those cons of n-tier.

From my experience, you should catch exceptions at the top level because that is where you have the most information about the the exceptions and most importantly the full stack trace.

There may be some reasons to catch exceptions in other tiers, however. But I can only think of one:

  1. The tier could handle them by itself. Ex: a connection failed and the tier re-tried it.

And also I would avoid logging exceptions at multiple tiers because it is not necessary.

This is my personal idea however. You can take a look here for more information & discussion:
Exception handling in n-tier applications?

Upvotes: 1

Related Questions