Sil*_*per 1 .net c# asp.net-mvc entity-framework
在我写入数据库的方法中,我处理错误,如下面的代码所示.在catch (DbUpdateException ex)我想重新抛出异常并在最后捕获它catch (Exception ex).
这可能吗,怎么做?下面的代码不会这样做.
using (Entities context = new Entities())
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
throw
new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
catch (Exception ex)
{
throw
new Exception("Error");
}
}
Run Code Online (Sandbox Code Playgroud)
以下会更好:
context.Office.Add(office);
retVal = context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
让泡沫除外.如果您要做的就是重新投掷,就不需要捕捉东西了.
注意:throw ex;将重置堆栈跟踪 - 您希望throw;正常运行.
| 归档时间: |
|
| 查看次数: |
1986 次 |
| 最近记录: |