目前,我正在进行一个项目,该项目分为几个部分,Core、UI等。在更改项目架构之前,我想知道在Core库中处理异常的最佳方法是什么?我是说,如何组织这些例外?例如,我可以用有意义的消息抛出系统异常:
// Database implementation within Core library
class Database
{
void Foo()
{
// ...
if (Something())
throw new InvalidDataException(message:"The something!");
else
throw new InvalidDataException(message:"It's not something!");
}
}
class UI
{
void ShowDatabase()
{
var database = new Database();
try
{
database.Foo();
}
catch (InvalidDataException e)
{
CleanUp();
MessageBox.Show(e.ToString());
}
}
}但是核心库不需要以任何方式与用户打交道。我说的对吗?好吧,还有另外一种方法。我可以抛出带有错误代码的系统异常作为异常消息,这样UI层就可以为用户本身选择警告消息:
static class ErrorCode
{
static string Something = "SomethingOccur";
static string NotSomething = "NotSomethingOccur";
}
class Database
{
void Foo()
{
// ...
if (Something())
throw new InvalidDataException(message:ErrorCode.Something);
else
throw new InvalidDataException(message:ErrorCode.NotSomething);
}
}
class UI
{
void ShowDatabase()
{
var database = new Database();
try
{
database.Foo();
}
catch (InvalidDataException e)
{
if (e.Message == ErrorCode.Something)
{
CleanUpSomthing();
MessageBox.Show(Resources.SomethingMessage);
}
else if (e.Message == ErrorCode.NotSomething)
{
CleanUpSomethingElse();
MessageBox.Show(Resources.NotSomethingMessage);
}
}
}
}现在它更灵活了,但是我认为e.Message == ErrorCode.Something看起来很难看。还有第三种方法,对任何情况分别实现例外:
class SomethingException : Exception
{
public SomethingException(string message = null, Exception inner = null) : base(message, inner) { }
}
class NotSomethingException : Exception
{
public NotSomethingException(string message = null, Exception inner = null) : base(message, inner) { }
}
class Database
{
void Foo()
{
// ...
if (Something())
throw new SomethingException()
else
throw new NotSomethingException();
}
}
class UI
{
void ShowDatabase()
{
var database = new Database();
try
{
database.Foo();
}
catch (SomethingException e)
{
CleanUpSomething();
MessageBox.Show(Resources.SomethingMessage);
}
catch (NotSomethingException e)
{
CleanUpSomethingElse();
MessageBox.Show(Resources.SomethingMessage);
}
}
}这看起来更好,但在某一时刻,每一种情况都会有数百个例外。听起来很糟糕。
那么,问题是--处理核心库中的异常的最佳方法是什么?也许有什么最佳做法?
对不起我的英语,顺便说一句。
发布于 2014-12-30 10:30:49
通用实践应该是这样的:
ArgumentNullException,InvalidOperationException)在异常类型与特定情况匹配的任何情况下。有很多.NET异常类,您需要对它们有一些了解,才能知道要抛出哪个类和何时抛出。CalculationExcepion。然后定义继承自它的类--指定特定类型的计算异常。使用这种方法,库的用户将能够捕获基本异常(覆盖许多错误案例),或者根据他们的偏好处理特定的异常。ErrorCode这样的属性,以免出现一个可能有50个不同错误代码的泛型异常类,对于您的核心库的用户来说,-this将是很难处理的。您可以在特定错误类型的有限数量的特殊情况下使用诸如ErrorCode这样的属性,比如在执行get请求时获得的HTTP代码: 200、500、404和一些其他代码--但仍然是有限的。https://stackoverflow.com/questions/27703628
复制相似问题