Creating custom errors for jquery.ajax ()

Suppose I have the following method in httphandler (.ashx):

private void Foo() { try { throw new Exception("blah"); } catch(Exception e) { HttpContext.Current.Response.Write( serializer.Serialize(new AjaxError(e))); } } [Serializable] public class AjaxError { public string Message { get; set; } public string InnerException { get; set; } public string StackTrace { get; set; } public AjaxError(Exception e) { if (e != null) { this.Message = e.Message; this.StackTrace = e.StackTrace; this.InnerException = e.InnerException != null ? e.InnerException.Message : null; HttpContext.Current.Response.StatusDescription = "CustomError"; } } } 

When I create the $.ajax() call for the method, I will return in the success callback, regardless of the fact that something goes wrong, and I got into the catch .

I have extended the ajax method a bit to normalize error handling, so regardless of whether it is a jquery error (parsing error, etc.) or my custom error, I will return in the callback.

Now, I would like to know if I should add something like

 HttpContext.Current.Response.StatusCode = 500; 

to finish the jQuerys error handler, or should I handle my

 HttpContext.Current.Response.StatusDescription = "CustomError"; 

in jqXHR object and accept its error when its there?

Let me know if something is unclear.

+4
source share
1 answer

You need to at least use the status code, since your $ .ajax may implement the failure function as follows:

 $.ajax({...}) .fail(function(xhr) { console.log(xhr.statusText); // the status text console.log(xhr.statusCode); // the status code }); 

If you want to just send the text directly to the user, you can use statusText. You can also, if you want, make different status codes for different errors (even if status codes are not ordinary), for example:

 $.ajax({...}) .fail(function(xhr) { switch(xhr.statusCode) { case 401: // ... do something break; case 402: // ... do something break; case 403: // ... do something break; } }); 
0
source

All Articles