简体   繁体   中英

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). 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. This way it is easier for you to debug your API by looking at the logs. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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