ASP MVC N-Tier Exception handling

2019-09-15 18:10发布

问题:

I am writing a service layer which uses Entity framework to get/set data from the database, and then pass it to an MVC web application. I am not able to decide what is the bext way to return database errors to the web application.

Should I throw an exception and the web application can handle it accordingly, or should I return a string/bool to convey that the database action has worked or not?

Any suggestion on what is the best practice?

Thanks

回答1:

You can either not handle them in your service layer, or you can normalize them using an exception class that you will create. For example:

public class DatabaseException: Exception
{
    public string TableName { get; private set; }

    public DatabaseException(string tableName, Exception innerException)
        :base("There a database error occured.", innerException)
    {
        TableName = tableName;
    }
}

Simply add whatever information you require to the exception class as properties and initialize them in the constructor.

It's really not the best practice to inform the higher levels about exceptions with return values, since most of the methods are already returning some data.



回答2:

You should not handle exception thrown out from web application, let exception thrown naturally, even from data access layer. With this way, it is easy for you for troubleshooting, esp in production stage. So, how to handle:

  1. Use custom error page for exceptions thrown out.
  2. Use HttpModule to log exception for troubleshooting. ELMAH, loggin module, works perfectly with ASP.NET MVC and alows you to view logs on web.