validating my mvc error handling - c#

I have this in place in global.asax, and I was hoping some folks could tell me if I'm making any glaring mistakes. This my first MVC application.
protected void Application_Error(object sender, EventArgs e)
{
if (HttpContext.Current.IsDebuggingEnabled)
{
throw Server.GetLastError();
}
Exception exception = Server.GetLastError();
Response.Clear();
//here I email (exception.ToString()) to a helpdesk system.
Server.ClearError();
Response.Redirect("/Error/");
}
Basically I wanted something that would:
a) Let me get the raw thrown exception when in debug.
b) In production, send the exception to a logging service / helpdesk app.
c) In production, hide the exception from the user and present a simple error page.
So far it seems to work just fine but was just curious if there's anything wrong with my approach.

Please refer custome error configuration in web config

Related

Losing USER information in ELMAH when using ADFS

I have an MVC web application using ELMAH to log unhandled exception. I'm now moving from windows authentication to ADFS authentication. The application has been adapted and is working fine. However now when I check the error, the user information is not there anymore. Which makes sense as ELMAH is using the context identity and not the claims to retrieve this info. Does anyone of you have an idea how I could do to get this information logged again?
You can enrich ELMAH errors using error filtering hook if you can accept a small hack. In short, you need to implement the ErrorLog_Filtering method in the Global.asax.cs file:
void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs args)
{
var httpContext = args.Context as HttpContext;
if (httpContext != null)
{
var error = new Error(args.Exception, httpContext);
error.User = GetUserFromDatabase();
ErrorLog.GetDefault(httpContext).Log(error);
args.Dismiss();
}
}
In the example, I update the User property with the value of a dummy method. How you want to implement this depends on how you would get the currently logged in user from ADFS. Finally, I log the error again and dismiss the initial (user-less) error.

Log failed IIS login (windows authentication)

In our application, we offer the use of Windows authentication. For this, the browser pops-up a window. When a user is logged in correctly, I can log this in the code after this:
if (HttpContext.Current.User.Identity.IsAuthenticated) c.Response.Redirect(General.PathPrefix() + "Default.aspx");
My question is, how can I log a user not getting authenticated, all code seems to stop when the login fails, and I get a 401 response.
You can log this error in the Global.asax file using the code below
public class CoolMvcApplication : System.Web.HttpApplication
{
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
//check here if this exception is an unauthorized access error, if so
Server.ClearError();
Response.Redirect("/not_loggedin");
}
}
Also you can achieve this by using filters and assert there if the error is unauthorized access and follow the same logic.

What to do/throw when you have hit a API limit

I am using a API with a limit, there is a high possibility that I could hit the limit.
I am wondering how people handle this? Do they check if they hit the limit and then throw an exception? If so what type of exception?
Are there any best practices?
I am able to see if I hit the limit like below:
if (!string.IsNullOrEmpty(result.error))
{
// we have hit a limit
}
This API is used for a MVC application.
I am caching the ActionResult methods with the API content ([OutputCache]). If the Action method does not recieve the API result then the view will be empty, but if i throw something it will end up on the custom errors page.
You should first log what happened using the information you receive from result.error and then create a custom exception and throw it including the original error message.
if (!string.IsNullOrEmpty(result.error))
{
// we have hit a limit
// log error
// throw new MyException(result.error);
}
Normally you can't do much in this type of error so you log it, throw the exception and it's somebody's else problem. When the exception is caught, you could decide, based on the exception type, to wait and retry.

.NET Retrieving Error StackTrace in Custom Error Page

I am running .NET 3.5 and IIS7.
I was trying to use customErrors to redirect to a custom error page that could still display the exception details, stack trace, etc. I had a hard time getting it to work, trying about 20 different approaches I found online (mostly on stackoverflow), some of which were slight variations of others. I preferred to have the redirect to happen in Web.config because I wanted the custom error page to be easily found/edited outside the code.
Here's what I finally got to work. I'm posting because I tried so many of the more complex approaches I found here and they didn't work for me, and just wanted to post the simple one that ultimately did.
Web.config:
<customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx" redirectMode="ResponseRewrite" />
Without the redirectMode="ResponseRewrite", I could not access the exception details from my custom error page.
Error.aspx
protected void Page_Load(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex != null)
{
if (ex.GetBaseException() != null) ex = ex.GetBaseException();
litErrorMessage.Text = String.Format("<div class=\"error\">{0}</div>", ex.Message);
litErrorStackTrace.Text = String.Format("<b>Source:</b>\n{0}\n<b>Stack Trace:</b>\n{1}\n", ex.Source, ex.StackTrace);
}
else
{
litErrorStackTrace.Text = "No Exception information available.";
}
}
I also tried using
HttpException ex = (HttpException)HttpContext.Current.Server.GetLastError();, as seen in some examples, but that did not work.
I also tried all kinds of code in Global.asax -> Application_Error, but it turns out it was not necessary. After trying all kinds of code there, including storing session variables, Application_Error is now empty.

exception catching in Global.ascx app_error

I have web application in asp.net and C#
I am trying to handle exceptions if they occur anywhere within this application.
like suppose the behaviour should be if and exception like this occurs
//generate your fictional exception
int x = 1;
int y = 0;
int z = x / y;
it should catch it in the app_error of the global.ascx file and redirect it to the Default.aspx page. i got the logging part but the redirect is not working as i still get the
Server Error in '/' Application.
page. or may be it is redirecting and getting killed in the middle..
this is what is there in global.ascx
protected void Application_Error(object sender, EventArgs e)
{
logger.Fatal(this.Server.GetLastError().GetBaseException());
logger.Info("FatalLogger Passed");
//get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();
Response.Redirect("~/Default.aspx?error=MessageHere");
}
this in the code in web.config
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" name="GUI" slidingExpiration="true" timeout="30" path="/">
</forms>
</authentication>
any ideas.. ill; be happy to provide more information.
Thanks
ok i want this approach for a reason because whenever there is an error the user get logged out and i dont want that to happen instead go to the default page
Have you tried calling Server.ClearError() before the redirect in Application_Error? It's been a while since I played with this, but I believe that if you don't call ClearError then the framework still thinks the error is unhandled.
Configure custom error pages
BTW, I recommend ELMAH for the logging part...
Try using Server.Transfer(page)
Also be wary of passing the error message via the Query String as it can open you up to XSS problems. Pass an error code and then display the message dependent on the code (using a switch statement)

Categories