Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a custom error message from Web Api to jQuery.ajax?

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

How do I get a custom error message, created by an HttpError parameter to CreateErrorResponse(), displayed by jQuery's deferred.fail()?

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

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

Here's a cut-down client that's trying to find the error message to display, "Failure to 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 is:

"error: Internal Server Error: {full stack here}"

What I want instead is:

"Failure to lunch."

like image 485
Boggin Avatar asked Aug 15 '13 12:08

Boggin


1 Answers

You could 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');
    }
});
like image 126
Darin Dimitrov Avatar answered Oct 22 '22 22:10

Darin Dimitrov