问题描述
我写它使用实体框架从数据库中获取/组数据,然后把它传递给一个MVC的Web应用服务层。我不能决定什么是数据库错误返回到Web应用程序的方式bext。
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.
我应该抛出一个异常,Web应用程序可以相应地处理它,或者我应该返回一个字符串/布尔传达数据库行动工作或没有?
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?
感谢
推荐答案
您可以不处理它们在你的服务层,也可以使用异常类,您将创建规范化它们。例如:
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.
这篇关于ASP MVC N层异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!