I would like to capture and log unhandled exceptions that occur in my Silverlight 5 application. I already have wired up the Application.UnhandledException delegate. The question is, after an exception has been thrown, what can and what can't I do? This Silverlight application is running in a C++ application that is hosting the WebControl (IE's engine) and this host is implementing the external function. So this is what the Application.UnhandledException's function looks like:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject;
// This is a reference to the
var external = External.Instance;
// loop through all the exceptions and call the hosts 'external' method so the
// host is able to write out the error to a local log file
while (external != null && ex != null)
{
external.LogException(ex.Message, ex.StackTrace);
ex = ex.InnerException;
}
// If the app is running outside of the debugger then report the exception using
// a ChildWindow control.
if (!System.Diagnostics.Debugger.IsAttached)
{
// NOTE: This will allow the application to continue running after an exception has been thrown
// but not handled.
// For production applications this error handling should be replaced with something that will
// report the error to the website and stop the application.
e.Handled = true;
ChildWindow errorWin = new ErrorWindow(e.ExceptionObject);
errorWin.Show();
}
}
The goal is to log the error and keep the application running.
A standard System.Diagnostics target to enable capturing using
DebugView, etc.
An asynchronous Web service target similar to the one in NLog.
An isolated storage target with deferred transfer to server semantics
more information in the following link:
Silverlight Logging framework and/or best practices
Related
I am trying to write a C# program that interacts with the Objective Electronic Records Document Management System [EDRMS] [see https://objective.com/] using its webtalk SOAP api.
One of the things I need to do is create a folder. To do that I am caling the createRequest api
The problem is that [sometimes] when I attempt to create a folder, the folder I want to use as the parent folder is unable to have folders of the type specified.
This problem is expected in the context of the program execution and cannot readily be avoided.
It relates to folders that were created in the UAT environment which was then refreshed from production - meaning some of the folder id's we have recorded in our DEV/UAT system relate to folders that no longer exist in the UAT objective environment. Thus it is entirely expected that it would fail when an attempt is made to create a sub-folder with a parent folder which cannot accept sub-folders.
Updating our DEV/UAT system to match production isn't an option right now, so I need to just handle these errors by skipping past them when the problem occurs.
What I want to do is catch this exception when it occurs, and handle the situation gracefully.
The problem that I have is, no matter how many try/catch exception handlers I place around the code that calls the web-service, C# fails to catch it and Visual Studio displays a dialog with the message 'This application is in break mode' and throws unhandled exception
I have been looking at this question
Visual Studio 2017 studio showing error 'This application is in break mode' and throws unhandled exception
but the settings that it suggests adjusting don't really stop the program seizing up.
This question also didn't help me:
Unhandled exception is not being caught by the handlers
since the program I'm running is a console application - my console app only uses one thread.
The code in question where the error occurs is:
...
createService.Url = URL_BASE + "/services/create";
// other code to set up the create service [which works just fine for many other calls]
...
createRequest createRequest = new createRequest();
// code to add the folder details to the create request
try
{
createResult = createService.send(createRequest); // <--- Problem occurs when we call the send method to call the soap api
}
catch (FaultException fe)
{
string message =
"Error when creating folder ";
Logger.LogException(message, fe);
throw new Exception(message, fe);
}
catch (SoapException se)
{
string message =
"Error when creating folder ";
Logger.LogException(message, se);
XmlQualifiedName code = new XmlQualifiedName();
throw new SoapException(message, code, se);
}
catch (Exception e)
{
string message =
"Error when creating folder ";
Logger.LogException(message, e);
throw new Exception(message, e);
}
When the error occurs, none of these catch's catch the error [including the final one which should catch everything not already caught].
Instead Visual Studio stops and displays a dialog box complaining of an uncaught exception.
Note that the "send" method looks like this:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("createsessionResult", Namespace="urn:objective.com")]
public createsessionResult send([System.Xml.Serialization.XmlElementAttribute(Namespace="urn:objective.com")] createsessionRequest createsessionRequest) {
object[] results = this.Invoke("send", new object[] {
createsessionRequest});
return ((createsessionResult)(results[0]));
}
Any pointers would be greatly appreciated. The send is actually calling a SOAP service, and the error occurs in the service being called. But what I want to do is detect that the call failed and then handle the situation by unravelling back up the call chain to a point in the processing loop where the issue can simply be noted and the process can skip this call and carry on.
Instead, the whole program fails at this point.
Any thoughts on how to get past this is greatly appreciated.
I have a windows phone app that makes web request. Each time I make a web request I have to handle network exceptions.
try
{
string testString = await httpClient.GetStringAsync("");
}
catch(Exception ex)
{
ex.Message == "net_http_message_not_success_statuscode"
}
Would it make more sense to have a global exception handler instead of having to write this code all the time?
If all of your calls funnel up to single location and the actual point of the exception isn't important, then a global exception handler would be just fine.
If you need to do some special handling closer to the point of the exception, then you'll need to keep the local exception handlers on each call.
I have developed a project which uses an external dll as FTPServer, I have created the FTP Server on my project like this:
private ClsFTPServer _ClsFTPServer;
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
The Code above creates an instance of FTP server class, the class starts the FTPserver on it's constructor, it works fine independently as a module while the clients send their request correctly, but when an incorrect request comes to FTP server it throws an exception and cause my application to crash.
How can I handle the exception thrown by the external dll to prevent my application from crashing?
I recently answered a similar (ish) question which may prove useful -
Catch completely unexpected error
EDIT. I have to agree with Hans' comment above - might be an idea to find another FTP server.
Just for completeness, here's the appdomain/thread exception setup from - http://msdn.microsoft.com/en-GB/library/system.windows.forms.application.threadexception.aspx
Application.ThreadException += new ThreadExceptionEventHandler (ErrorHandlerForm.Form1_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
In case of using external unmanaged\unsafe code, .NET (above .net 4) by default cannot handle Memory Access Violation exceptions that happens inside of dll code.
in order to catch these kind of exceptions, there is three things to do. I did them and it worked for me:
Add these Attributes to the method that exception occurred inside of it :
(the method that calls the method of the unmanaged code.)
[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
Add this tag to App.Config file below runtime tag :
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true"/>
<!-- other tags -->
</runtime>
Catch these kind of exception by using System.AccessViolationException exception type :
try{
//Method call that cause Memory Access violation Exeption
}
catch (System.AccessViolationException exception)
{
//Handle the exception here
}
What i said is just the cure for these type of exception. for more information about this exception's ego and how this approach works, see System.AccessViolationException
You've probably already tried this, but just in case, have you tried wrapping it in a try catch?
try
{
_ClsFTPServer = new ClsFTPServer(FTPUserName, FTPPassword, FTPPath);
...
}
catch(Exception e)
{
...
}
By putting a try...catch block around every call into the object and its methods.
Something like:
try
{
// use the DLL in some way
}
catch (Exception e)
{
// Handle the exception, maybe display a warning, log an event, etc.)
}
Also note that while running under Visual Studio, if you go to the "Debug" menu and select "Exceptions..." it will allow the debugger to break on ALL exceptions if you start your program under the debugger, and not just unhandled exceptions. Just click the 'Thrown' checkbox next to "Common Language Runtime Exceptions".
I develop a desktop application that have to save running process with xml file.
I have design and test already.
But I want to know how the catch the unexpected error that will make the application terminated to start save the running process.
It's possible the following links may help:
http://www.csharp-examples.net/catching-unhandled-exceptions/
http://www.switchonthecode.com/tutorials/csharp-tutorial-dealing-with-unhandled-exceptions
You're (I believe) looking to bind to AppDomain.CurrentDomain.UnhandledException
You want to use the try / catch construct. Basically you wrap the code you are concerned is going to error in a try { } block and then immediately following is a catch { } block of code that will run if an error was encountered. In this section you could do things like log the error, attempt to save to a different location, etc.
Refer to http://msdn.microsoft.com/en-us/library/0yd65esw%28v=vs.80%29.aspx for examples and information.
If your application is a web application, you can handle it in this manner:
//Method in global.asax.cs
void Application_Error(object sender, EventArgs e)
{
var lastError = Server.GetLastError();
//Log it using log4net
}
Additionally you can consider using elmah
I'm using the .NET Exception Management Application Block (EMAB).
As part of this I am implementing IExceptionPublisher classes.
However, I am wondering what happens if these publishers encounter an Exception.
I had a bit of a look around and apparently they are meant to do something like this:
try
{
/* Normal Exception Publishing */
}
catch
{
ExceptionManager.PublishInternalException(exception, additionalInfo);
}
Source:
One caveat: what happens if there is
an exception in our custom publisher
code, preventing the publishing to
MSMQ? For that, we turn to the
ExceptionManager.PublishInternalException
method, which will publish the
exception to the default publisher,
which is the Windows application event
log.
However, PublishInternalException is both protected and internal so I would have to be implementing ExceptionManager, not IExceptionPublisher, to access it.
It handles itself, publishing both the original Exception and the Exception your IExceptionPublisher threw to the Application Log
The idea to manually call PublishInternalException must have been related to an early beta. The current ExceptionManager wraps the IExceptionPublisher calls in its own try-catch which calls PublishInternalException itself. If you check out the code in Reflector it basically does this:
/* Foreach publisher */
Exception originalException;
try
{
PublishToCustomPublisher(originalException, additionalInfo, current);
}
catch (Exception publisherException)
{
/* Both of these calls use the DefaultPublisher which is the Application Log */
PublishInternalException(publisherException, null);
PublishToDefaultPublisher(originalException, additionalInfo);
}
You may also want to check out the newer Enterprise Library Exception Handling Application Block