10

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."

3
  • Do you mean "failure to launch" not lunch Commented Aug 15, 2013 at 12:28
  • 3
    @KevinHolditch I was hungry! Commented Aug 15, 2013 at 13:12
  • 1
    so am I now I've read your question :) Commented Aug 15, 2013 at 13:16

1 Answer 1

8

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');
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

This is where I'm getting confused. jqXhr.responseText.Message has the error message from the InternalServerError ("An error has occurred."), not the custom message I put into HttpError.
I made a mistake in my answer. You should use alert(error.Message) instead of alert(error).Message. The Message property will contain the text Failure to lunch.. I have just tested it and it worked fine. Could you show the value of jqXhr.responseText?
I was confused, it turns out, because my test case here was throwing another InternalServerError exception which was being returned before my CreateErrorResponse code was being hit. The Web API will comfortably cope with this in the absence of any try..catch code. You're quite right, the Message property is what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.