Application_Error Called but there is no Exception - asp.net-mvc

While debugging my MVC 4 application in VS2010 SP1, the Application_Error() handler was invoked but Server.GetLastError() was null.
protected void Application_Error()
{
var exception = Server.GetLastError();
// exception is null. How is that possible?
}
MSDN states Application_Error is
called if an unhandled exception occurs anywhere in your ... application... You can get information about the most recent error from the GetLastError method.
The MSDN docs for Server.GetLastError() states
Return value: The previous exception that was thrown.
How can I possibly be in a state where Application_Error() was called but Server.GetLastError() returns null?

Are you using custom error handling in your web.config? I believe that if the browser issues a redirect, the previous exception will be lost. Take a look at this answer and see if your situation is similar.

Related

Xero API General Error handling

Using ASP.NET MVC 5 and the Xero.API.SDK.2.2.1.13.
I'm trying to handle all possible errors thrown when calling the Xero Api. I'm attempting this through over riding the OnException action within my BaseController. This successfully catches all errors thrown but I am unable to access the list of ValidationErrors which appears to be contained within the filterContext object (see below) when I'm debugging. I'm also unable to create a XeroApi.ValidationException object from the filterContext object.
Does anyone know how to access the ValidationErrors in this instance? Or have a more suitable way of handling all xero and other related errors within a single controller?
protected override void OnException(ExceptionContext filterContext)
{
//Below line results in error: "cannot convert System.Exception to
ValidationException. An Explicit conversion exists".
ValidationException ex = filterContext.Exception;
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
}
Answer provided by Henzard Kruger on the Xero Community forum:
Just hack the Xero dll. You need to deal with the error in https://github.com/XeroAPI/Xero-Net/blob/master/Xero.Api/Infrastructure/Http/XeroHttpClient.cs#L105 then just recompile the DLL.
Issue was resolved after following the above advice.

MVC Application FaultException Thrown How to get to display Error page

I have mvc 3 application which when a Standard generic throw new Exception is thrown in code the error page from Views\Shared\error.cshtml is shown. This is done by simply setting <customErrors mode="On"/>. (This is As expected and as Desired)
The application is using WCF services in middle tier which when these services generate FaultException MVC is not showing up the error page it is showing details of the web service call to the user on screen. All I want to do is handle the error in my code and show the user the Error.cshtml. I have tried changing global asax but this dosent work.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
if (exception.GetType() == typeof(FaultException))
{
throw new Exception("There was a fault exception that i do not want to show details of to user.");
}
}
Try creating an ErrorController as asp.net MVC will try to resolve the link you specified in the web.config as {Controller}/{View} unless you specify it to ignore that page. Also, you may want to apply an attribute to handle exceptions instead.
You can also create a error controller/view and in your catch block redirect to the custom error page of your choosing
try
{
foo.bar()
}
catch(SpecificException)
{
RedirectToAction("500", "Error");
}

Application_Error: how to save exception information?

I am using the following code to capture exceptions in the application, and save them in the Session object. The exception is then retrieved from Session in the error handler page to which the app automatically redirects:
protected virtual void Application_Error(Object sender, EventArgs e)
{
try
{
Exception ex = Server.GetLastError();
Session["exception"] = ex;
}
catch { }
}
I have one problem with this code:
Session is not available if a malformed path gets in: "example.com/"foo" - Exception is thrown when accessing it, and NULL is retrieved from Session object in the error page
What is a better way to save exception information in the application and pass it to the error handler action?
If you are trying to log exceptions then take a look at the elmah project.
Scott Hanselman has a good introduction
If you can't use ELMAH for any reason,
http://www.genericerror.com/blog/2009/01/27/ASPNetMVCCustomErrorPages.aspx

How to get rid of that HTML error report in ASP.NET MVC?

All I need would be just the error message in plain text. But ASP.NET is doing some HTML report output from every error.
I have a jquery ajax call and when an error is thrown I'm getting all that crap over to the client side.
I've created a filter attribute but didn't helped.
public class ClientErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var responce = filterContext.RequestContext.HttpContext.Response;
responce.Write(filterContext.Exception.Message);
responce.ContentType = MediaTypeNames.Text.Plain;
filterContext.ExceptionHandled = true;
}
}
EDIT
I'm seeing this
and I'd like to see just what is in here filterContext.Exception.Message
It looks to me like the reason why you cannot correctly handle the exception is because it happens outside of the MVC pipeline. If you look at the stack trace in the code you posted there is no reference to System.Web.Mvc code (the firing of exception filters when an exception occurs is called from ControllerActionInvoker.InvokeAction).
The stack trace indicates that the exception happens late in the ASP.NET pipeline (OnEndRequest) and that it's coming through the Autofac component.
To capture this error you would have to subscribe to the HttpApplication's Error event. See the following article on creating a global error handler: http://msdn.microsoft.com/en-us/library/994a1482.aspx . In this event you can handle the error and redirect to a custom error page.
you need to return a ContentResult
ContentResult result = new ContentResult();
result.Content = filterContext.Exception.Message;
result.ContentType = MediaTypeNames.Text.Plain;
filterContext.Result = result;
filterContext.ExceptionHandled = true;
Since you're using JQuery and WCF (by the details of your error), you might want to take a look at this article on how to handle service faults elegantly between jQuery and WCF - you might have to rework your service if you are able to do so.

How can send back my own 404 error message in ASP.NET , but as json?

i'm trying to send back a simple error message as Json, with the HTTP code as 404.
So i started out writing my own IExceptionFilter that checks to see the exception. To keep this simple, if the exception throw is of type ResourceNotFoundException then i set the code to 404. Otherwise everything else if 500.
Now, the problem is .. the default IIS7 404 error message is returned :( my code is called .. but it seems to bypass it (later on in the pipeline)...
is there some trick i need to do?
do I need a custom error handling (in the web config) to be turned on or something?
Edit:
I'm trying to do what twitter does. Their Http Response Code documentation shows / explains some examples how they handle 404's, etc.. and i'm wanting to do that in my MVC app.
Edit 2:
The code i've done is listed here, for anyones reference :)
When you are handling your exception, are you setting ExceptionHandled to true?
Here's a quick example...
HandleException(ActionExecutedContext filterContext)
{
Exception exception = filterContext.Exception;
//Check if our exception has been handled.
if (filterContext.ExceptionHandled == false)
{
//Do your exception stuff
filterContext.Result = YourExceptionMessageAsAnActionResult();
//Set it as null.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
}

Resources