Created
June 26, 2015 18:42
-
-
Save tracker1/ab061e0ff4b3aed180d7 to your computer and use it in GitHub Desktop.
Application_OnError Handler, take care of JS expected responses.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protected void Application_Error(object sender, EventArgs e) | |
{ | |
var status = 500; | |
// Get the error details | |
var lastError = Server.GetLastError(); | |
HttpException lastErrorWrapper = Server.GetLastError() as HttpException; | |
if (lastErrorWrapper != null) | |
{ | |
status = lastErrorWrapper.ErrorCode; | |
lastError = lastErrorWrapper.InnerException ?? lastError; | |
} | |
string lastErrorTypeName = lastError.GetType().FullName; | |
string lastErrorMessage = lastError.Message; | |
string lastErrorStackTrace = lastError.StackTrace; | |
// Filter logging for request-level errors | |
if (lastError is System.ArgumentException) | |
{ | |
if (lastErrorMessage.IndexOf("parameters dictionary") >= 0) | |
{ | |
status = 400; //invalid input parameter - MVC | |
} | |
} | |
//server-side error - log it | |
if (status >= 500) | |
{ | |
// TODO: Log Error Message Here | |
} | |
//set the response status to match the set status code | |
if (status >= 100 || status < 600) Response.StatusCode = status; | |
//return as JSON for appropriate requests | |
var isJson = Request.AcceptTypes.Where(at => at.IndexOf("json") >= 0).Count() > 0; | |
var isJS = Request.AcceptTypes.Where(at => at.IndexOf("javascript") >= 0).Count() > 0; | |
var isJsonP = !string.IsNullOrWhiteSpace(Request.QueryString["callback"]); | |
if (isJsonP || isJson || isJS) { | |
var data = JS.StringifyFormatted(new | |
{ | |
error = new | |
{ | |
code = Response.StatusCode, | |
message = lastError.Message, | |
details = JS.ConvertError(lastError) | |
} | |
}); | |
if (isJsonP) | |
{ | |
//JsonP request, wrap callback | |
Response.ContentType = "application/javascript"; | |
Response.Write(string.Format("{0}({1})", Request.QueryString["callback"], data)); | |
} | |
else if (isJson) | |
{ | |
//Json request, send as-is | |
Response.ContentType = "application/json"; | |
Response.Write(data); | |
} | |
else if (isJS) | |
{ | |
//JavaScript request - wrap with alert. | |
Response.ContentType = "application/javascript"; | |
Response.Write(string.Format("alert('Unhandled server error.');console.error('Server Error:',{0});", data)); | |
} | |
Server.ClearError(); //handled with JS response | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment