Returning error messages from a C# DLL to a C# program?
I have spunoff a winforms program class into a separate DLL. The DLL uses try-catch on all is methods to capture errors. When still a winforms class I would catch the error, log it, and then notify the user via a MessageBox. With the DLL I am catching the开发者_如何学编程 error, logging it - but am not sure how to notify the user there was a error?
How can I best notify the user that there was a error in the DLL?
If you want to log it, then okay, catch it, log it, then throw an appropriate exception and let the consumer decide how best to deal with it. If you've got no value to add, and no semantics to change, then just do this within your DLL:
catch(SpecificException ex)
{
LogException(ex);
throw;
}
If you do have more information to add, then throw an appropriate new exception, using an appropriate constructor that includes that caught exception as the innerException
value.
What you shouldn't do (I've seen far too many people try) is "smartly" determine what type of application is consuming the DLL, and attempt to display UI from within the DLL. Even if you do get all of the current usage scenarios correct ("It's only ever used by WinForms applications"), you've now limited future reuse potential.
You should let the consumer decide its own error handling strategy, rather than try to impose one from within the DLL.
Don't catch the error! Catch it, log it then rethrow it if you must, but don't swallow the exceptions. Let it propagate up to the host application which can then deal with it as it likes (e.g. show a message box).
one way I can think of is throwing a generic exception from DLL , which you can catch in you app and then display the message accordingly returned from the dll. seems not so wise.
You should continue to throw the exception in your dll (after you have logged it)
A good practice is to deal with errors and exception at the last possible chance. In your case that should be in the winform application.
As others has stated, throw the exception after logging. If you got a separate thread/timer in that dll and there is nothing to throw it to, notify through an event that the host application can listen to.
精彩评论