How to properly handle errors in a n-level application?

advertisements

I have struggled with this since day 1. It probably doesn't help that I've been surrounded by a lot of code that doesn't even handle errors at all.

Anyway, I'm working with WebForms in your traditional n-tier design: UI->BLL->DAL. Usually what I do (and I know it's not right) is to try/catch my data operations. If there is an exception I simply throw it to bubble up.

try
'db operations
catch ex as exception
throw
finally
'close connections
end

So then it bubbles up to the BLL and in there is another try/catch where I'll log the error. Now I want to alert the user that something is wrong so I throw it again, this way it bubbles to the UI. At the UI level, I will wrap in a try/catch and if there's an error I'll display a friendly message to them.

What are your thoughts? What can I do better here?


As I understand, you have three try/catches - one for each tier: DAL, BLL,UI.

You should only catch when you are going to do something about it.

From what I understand, you simply retrow from DAL so there's no need for it.

From BLL you log the exeption and that is a good practice since you'll be able to collect data about exceptions to eventually improve the application.

Then you catch at the UI tier to translate the exception into something user friendly. That's OK.

So I would only get rid of the try/catch from the DAL layer - if you really don't do anything more than retrowning the exception.

In some scenarios, it can be usefull to add an identifier at the BLL that is passed to the UI exception and shown to the end users so that if they call support, support personel can correlate the given Id with an exception on the server's log.

That can be done, for instance, adding a Guid or something else meaningfull and unique to Exception.Data collection.