Where to log exceptions?

208 views Asked by At

I have a multi-layered web application, layers are like below.

  1. MyApp.Models
  2. MyApp.Views
  3. MyApp.Controllers
  4. MyApp.Services
  5. MyApp.Repository.EF

In this architecture i have a seperated controllers class project as you may guess. Let's imagine that i want to add a category into db in this application.

For this transaction i follow these project steps below,

Controllers > Services > Repository > DB

For this transaction i follow these method steps in projects below,

CreateAction > CreateCategory > InsertEntity > CategoryTable

In all of those methods in layers, i use try-catch blocks for loging any exception occurs. I do wonder it is correct or not? I really bored to write try-catch blocks for loging things in every following steps for possible errors in every tier.

What is the best practice to log in multi-layered application like mine?

2

There are 2 answers

0
Max On

As a Java developer, I would create some new types of Exceptions (Runtime, Checked, etc.) with a constructor accepting other exceptions instances as parameters and/or other (business or technical) parameters. In this constructor I may log what I want. By this way, I will avoid all these try catch blocks done for logging.

1
L-Four On

Normally you would add a global exception handler, in which you log the exception and convert it to a suitable format to sent to the user (Error page, WCF fault, HTTP error etc, depending on the technology you are using.

This means that you don't need any try/catch in your service, business or other layer; unless you have some specific logic to execute. Instead, you don't worry about catching exceptions all the time because they are handled by the global exception handler and so its inner details are not exposed, but logged automatically.

For an example on how to do it in ASP.NET MVC: look here.