How to get my own error message from Web Api in jQuery.ajax?

This code uses the Microsoft Web Api Http and jQuery stack.

How to get my own error message generated by the HttpError parameter for CreateErrorResponse () displayed by jQuery deferred.fail ()?

An example of creating an error response for testing purposes in ApiController:

public HttpResponseMessage Post(Region region) { var error = new HttpError("Failure to lunch."); return this.Request.CreateErrorResponse( HttpStatusCode.InternalServerError, error); } 

Here's a cutting client who is trying to find an error message to display "Impossibility of lunch."

 $.ajax({ type: 'POST', url: 'api/region', contentType: 'application/json; charset=utf-8', data: JSON.stringify(region) }) .fail(function (jqXhr, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText); }); 

What will be displayed:

": Internal server error: {full stack here}"

Instead, I want:

"Refusal of dinner."

+7
jquery c # asp.net-web-api jqxhr
source share
1 answer

You can parse the responseText string and then use the Message property:

 .fail(function (jqXhr, textStatus, errorThrown) { if (jqXhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) { // only parse the response if you know it is JSON var error = $.parseJSON(jqXhr.responseText); alert(error.Message); } else { alert('Fatal error'); } }); 
+6
source share

All Articles