I am having an issue with recording an exception to AWS X-Ray.
Here is what is in Application_Error:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
if (exception != null)
{
var InnerException = exception.InnerException;
Session["error"] = String.Format("{0} ::: {1}", exception.Message, exception.StackTrace);
try
{
AWSXRayRecorder.Instance.AddException(exception);
}
catch (Exception ee)
{
// ignore errors for XRay
}
}
Server.ClearError();
}
However, an error is thrown on the AddException line stating "Segment doesn't exist in CallContext"
First time trying to get X-Ray going. Any advice? Are there any tutorials that anybody has run into that may help?
The default behavior of XRay is to throw an exception if you are attempting to access a Segment, and none is currently setup in the current context. You can see the default behavior mentioned in the environment variables documentation.
As that documentation points out, you can set the AWS_XRAY_CONTEXT_MISSING environment variable on your EC2 instance to LOG_ERROR to adjust this behavior.
Alternatively, you can use the ContextMissingStrategy property to change this behavior within the code. Documentation link.
Set AWS_XRAY_CONTEXT_MISSING to LOG_ERROR can stop AddException to throw the "Segment doesn't exist" exception, but this also means nothing gets recorded to XRay service.
To really solve the problem, you should create a Segment at the beginning of your logic. When you are writing an ASP.NET Web API application, you can add an interceptor to automatically create a segment for each incoming request. There is a sample application you can try.
https://github.com/awslabs/aws-xray-dotnet-webapp
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 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
I'm running some code that only has to run once but it depends on external resources and may fail. I want the error to appear in the event log but I do not want the user to see it. I'd like to avoid using custom error pages if possible.
I could catch the exception and write it to the event log myself but I'm concerned that I can't guarantee what the name of the asp.net event source would be (it appears to change depending on the framework version.) I also can't create my own event source since that requires administrative permissions.
The approach that I'm currently working towards is a bit of a hack (which doesn't work yet) and it looks like this:
public void Init(HttpApplication context)
{
try
{
throw new Exception("test"); // This is where the code that errors would go
}
catch (Exception ex)
{
HttpContext.Current.Application.Add("CompilationFailed", ex);
}
}
private void context_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Application.AllKeys.Contains("CompilationFailed"))
{
// It failed on Init - we can't throw an exception there so lets try it here
var origEx = (Exception)HttpContext.Current.Application["CompilationFailed"];
// Only ever do this once
HttpContext.Current.Application.Remove("CompilationFailed");
// This should just look like a normal page load to the user
// - it will be the first request to the site so we won't be
// interrupting any postbacks or anything
HttpContext.Current.Response.AddHeader("Location", "/");
HttpContext.Current.Response.StatusCode = 301;
try
{
HttpContext.Current.Response.End();
}
catch (ThreadAbortException ex)
{
throw origEx;
}
}
}
Ideally what I would really like is a RecordException() method within IIS if anything like that exists.
I recommend Elmah for ASP.NET.
sounds like you want to be notified when there is an error but don't want the user to know about it. you could have the page redirect (if Fatal Error) or finish executing the rest of the file/page after sending you an E-mail or writing to data source that you have access to.
I'm having problems working with EntityFramework. While below peace of code works fine on my PC, when it's transported to a VPS (with everything properly preinstalled), it gives me a Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object, but the message box that is supposed to catch this does not show up. Any suggestions?
Thank you in advance.
var cc = new CopierContext();
try
{
MessageBox.Show(cc.Database.Connection.ConnectionString.ToString());
var matchingProviders2 = cc.Providers.Where(prov => prov.Login == "batman");
}
catch (Exception e)
{
MessageBox.Show(e.InnerException.Message);
}
Update:
I finally got to the core of the problem. The reason is: I've had .NET 4 on VPS, while application was developed using .NET 4.5. Installing the latter one removed all problems. Thank you for all your help.
I don't know how you are running it on your VPS, but if it is not launched under the interactive user account, your message boxes will not show up.
Well from the docs on the Exception.InnerException Property
The InnerException property returns the same value as was passed into
the constructor, or a null reference
Since you're catching any old exception catch (Exception e) its quite possible that the exception that's being thrown isn't the exception you were expecting and doesn't have a InnerException. This means your catch block may be raising an exception.
There are several actions you could take.
Do not catch System.Exception exception in anything but a top level exception handler. Only catch exceptions you know what to do with. Which leads to...
Set up a top level exception handler
Finally when logging or displaying exception messages at least make sure you have an inner exception before you try and use it.
MessageBox.Show( (e.InnerException != null ? e.InnerException : e).Message );
Don't use a MessageBox as it is a service; log them to disk instead such that you can recall them, or perhaps automatically mail them to you such that you are up to date on problems occuring.
You will also want to add e.InnerException.StackTrace to the log.
My bet is that you did not configure something (or did not configure it correctly) and cc.Database.Connection.ConnectionString is null. Calling .ToString() causes the NullReferenceException. That's why you don't see the message box. As other people said - using MessageBox for this kind of debugging is not a good idea. In the catch you should print not message but e.ToString() it will show the stack trace that should point to the place where the problem is.
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