更具体地说,当异常包含自定义对象时,这些自定义对象本身可以是自身可序列化的
举个例子:
public class MyException : Exception
{
private readonly string resourceName;
private readonly IList<string> validationErrors;
public MyException(string resourceName, IList<string> validationErrors)
{
this.resourceName = resourceName;
this.validationErrors = validationErrors;
}
public string ResourceName
{
get { return this.resourceName; }
}
public IList<string> ValidationErrors
{
get { return this.validationErrors; }
}
}
Run Code Online (Sandbox Code Playgroud)
如果此异常序列化和反序列化,则不会保留两个自定义属性(ResourceName和ValidationErrors).属性将返回null.
是否有用于实现自定义异常序列化的通用代码模式?
我有以下代码,当我点击表格时,它会检索记录详细信息:
public ActionResult City(string rk)
{
try
{
var city = _cityService.Get("0001I", rk);
if (city == null)
{
throw new ServiceException("", "Error when fetching city " + rk);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我应该使用什么样的例外来解决这个"没有记录"的问题?我看到有不同类型的异常,但我不确定哪个是合适的,或者即使我正确编码.
我是ASP.NET的新开发人员,这是我第一次使用Linq-to-Entities和Entity Framework。我现在的问题是关于使用最佳实践来连接实体或数据库。我知道try-catch块非常昂贵。但是,当我需要连接到数据库时,是否应该使用它们?我问这个问题是因为我有大约20个实体,并且在我的数据访问层中,对于每个这些实体我都有所有的GetData()方法。您能对此提出建议吗?
C#代码:
public static IEnumerable<Items> getData()
{
List<Items> itemsList = new List<Items>();
try
{
using (ItemsDBEntities context = new ItemsDBEntities())
{
itemsList = (from item in context.Items
select new Items()
{
ID = item.ID,
Code = item.Code,
Name = item.Name,
StatusID = item.StatusID
}).ToList();
}
}
catch (EntityException ex)
{
//something wrong about entity
}
catch (Exception ex)
{
//Don't know what happend...
}
return itemsList;
}
Run Code Online (Sandbox Code Playgroud) 我想使用其他信息来修改Message属性Exception。例如从生成SQL的EF。
但是我不想失去任何原始东西Exception。这会让我迷失stacktrace:
catch (Exception ex)
{
throw ex;
}
Run Code Online (Sandbox Code Playgroud)
这些Exception来自数据层。我想要throw他们,以便可以使用登录Elmah。
我有什么选择?
根据这篇文章,使用Exception类的Message字段不是一个好的编程习惯.
但是,当我尝试ArgumentException在我的项目中抛出异常(例如)时,如何添加自定义异常信息?我应该使用Exception.Data房产吗?
而不是使用:
throw new ArgumentException("My Custom Info.");
Run Code Online (Sandbox Code Playgroud)
我应该使用:
ArgumentException ex = new ArgumentException();
ex.Data["CustomInfo"] = "My Custom Info.";
throw ex;
Run Code Online (Sandbox Code Playgroud)
如果我不使用Message字段,代码会变得很麻烦.
不使用Exception类的Message字段是一种好习惯吗?
提前致谢.