【发布时间】:2011-12-24 03:12:35
【问题描述】:
我现在使用以下代码在我的服务层中捕获错误并引发异常:
...
if (pk == null || rk == null) return null;
try
{
var item = repo.GetPkRk(pk, rk);
return (T)item;
}
catch (Exception ex)
{
throw new ServiceException("", typeof(T).Name + rk + " data retrieval error");
}
...
ServiceException 类:
public class ServiceException : ApplicationException {
public Dictionary<string, string> Errors { get; set; }
public ServiceException() : this(null) {}enter code here
public ServiceException(string key, string message)
{
Errors = new Dictionary<string, string>();
Errors.Add(key, message);
}
public ServiceException(Exception ex)
: base("Service Exception", ex)
{
Errors = new Dictionary<string, string>();
}
}
然后在我的控制器中捕获错误消息:
catch (Exception e) { log(e); }
终于在log方法中处理了:
protected void log(Exception ex)
{
if (ex is ServiceException)
{
ModelState.Merge(((ServiceException)ex).Errors);
} else {
Trace.Write(ex);
ModelState.AddModelError("", "Database access error: " + ex.Message);
}
}
任何人都可以评论这是一个好还是坏的方法。我之前有过关于捕获内部异常的评论。这可能吗?如果可以,那么我如何才能捕获并保留内部异常详细信息。
更新 1
我修改了异常类,所以有一个使用 ex 的构造函数。不确定这是否理想,但我认为它有效。任何关于如何改进的建议将不胜感激。
更新 2
下面的代码失败并显示一条消息
Error 2 Property or indexer 'System.Exception.InnerException' cannot be assigned to -- it is read only
我不知道如何解决这个问题。
public class ServiceException : ApplicationException {
public Dictionary<string, string> Errors { get; set; }
public ServiceException() : this(null) {}
public ServiceException(Exception ex, string key, string message)
{
Errors = new Dictionary<string, string>();
InnerException = ex;
Errors.Add(key, message);
}
public ServiceException(string key, string message)
{
Errors = new Dictionary<string, string>();
Errors.Add(key, message);
}
public ServiceException(Exception ex)
: base("Service Exception", ex)
{
Errors = new Dictionary<string, string>();
}
}
【问题讨论】:
-
请看答案。我已经修改过了。
-
不要从
ApplicationException派生:stackoverflow.com/questions/52753/…,blogs.msdn.com/b/kcwalina/archive/2006/06/23/644822.aspx
标签: c# exception exception-handling