我正在为一些数据操作编写一个API,这些天我面临一个我无法回答自己的问题:D
我已经创建了一个扩展.net应用程序异常类的异常类,因为我希望在API每次引发异常时添加一些要执行的功能。 例如,我想通过短信和电子邮件提醒错误消息和堆栈跟踪,我想通过Log4net记录内部异常。 我不知道这是否是使用自定义异常类的好方法,或者是否滥用了自定义异常的含义。
我已经阅读了关于如何在c#中扩展异常的这篇文章 ,所以在这里我们以我的代码为例:
public class CustomExceptionClass : Exception { /// <summary> /// I use custom functionality here everytime this exception occures /// </summary> /// <param name="errorMessage">error message</param> /// <param name="innerEx">Inner exception that cause this exception</param> public MyCustomException(string errorMessage, Exception innerEx) : base(errorMessage, innerEx) { //log exception _log.ErrorFormat(errorMessage, innerEx); //alert via sms and email AlertMailer.SendAlertMessage(errorMessage, innerEx, innerEx.Message); } }I am writting an API for some data manipulation these days and I have faced a question that I cannot answer myself :D
I have made an exception class that extends the .net Application Exception class because I want to add some functionality there to be executed everytime the API throws an exception. For example I want to alert the error message and stacktrace via sms and email and I want to log the inner exception via Log4net. I don't know if this is a good aproach to use with the custom exception class or if I overused the meaning of the custom exceptions.
I have read this article about how to extend the Exception in c# so here we go with my example of code :
public class CustomExceptionClass : Exception { /// <summary> /// I use custom functionality here everytime this exception occures /// </summary> /// <param name="errorMessage">error message</param> /// <param name="innerEx">Inner exception that cause this exception</param> public MyCustomException(string errorMessage, Exception innerEx) : base(errorMessage, innerEx) { //log exception _log.ErrorFormat(errorMessage, innerEx); //alert via sms and email AlertMailer.SendAlertMessage(errorMessage, innerEx, innerEx.Message); } }最满意答案
我认为通过抛出自定义异常来做日志记录和警报是一种有效的技术。
但是,您不应该在异常构造函数中执行日志记录和警报。 相反,您应该捕获API中所有入口点的自定义异常,并在catch块中执行日志记录和警报。 例如:
void MyApiFunction() { try { // do data manipulation } catch(MyCustomException ex) { _log.ErrorFormat(ex.ErrorMessage, ex.InnerEx); AlertMailer.SendAlertMessage(ex.ErrorMessage, ex.InnerEx); } }I think that doing logging and alerting by throwing a custom exception is a valid technique.
However, you shouldn't do the logging and alerting in the exception constructor. Instead you should catch the custom exception in all entry-points to your API and do the logging and alerting in the catch block. For example:
void MyApiFunction() { try { // do data manipulation } catch(MyCustomException ex) { _log.ErrorFormat(ex.ErrorMessage, ex.InnerEx); AlertMailer.SendAlertMessage(ex.ErrorMessage, ex.InnerEx); } }更多推荐
发布评论