简体   繁体   English

库中的异常处理

[英]Exception Handling in libraries

Is there any problem with the following library code? 以下库代码是否有问题?

try
{
    //
}
catch (Exception ex)
{
    CustomLogger.Log(ex.ToString()); //Write to log file
    throw;
}

I have read somewhere that exception handling is best left to Application 我读过某个地方,最好将异常处理留给应用程序

A Framework really shouldn't have its own logging. 框架实际上不应该拥有自己的日志记录。 It should allow the Application to supply a logging provider. 它应该允许应用程序提供日志记录提供程序。

If the Application supplied the logging provider in a case like this, then the actual code would be fine (logging the Exception and then re-throwing). 如果应用程序在这种情况下提供了日志记录提供程序,那么实际的代码就可以了(记录Exception然后重新抛出)。 Otherwise, just let the Exception bubble up for the Application to log how it sees fit. 否则,只需让异常冒泡,以使应用程序记录其认为合适的方式。

If you insist you can have the API log the error and state of the program. 如果您坚持认为,可以让API记录错误和程序状态。 This way it is easier for you to debug your API by looking at the logs. 这样,您可以通过查看日志来更轻松地调试API。 On top of this, you should rethrow the exception so the caller knows about the error and try to handle it in a meaningful way. 最重要的是,您应该重新抛出异常,以便调用者知道该错误并尝试以有意义的方式对其进行处理。 If you just log and not throw, the caller will be confused or might need to watch the log file for changes and infer the exceptions from there. 如果您只是记录而不扔,则调用者将感到困惑,或者可能需要监视日志文件中的更改并从那里推断异常。

My point is, throw it even if you log it. 我的意思是,即使您记录了它,也要扔掉它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM