10

此代码使用 Microsoft Web Api Http 堆栈和 jQuery。

如何获取由 jQuery 的deferred.fail()显示的由CreateErrorResponse()的HttpError参数创建的自定义错误消息?

在 ApiController 中为测试目的创建错误响应的示例:

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

这是一个精简的客户端,它试图找到要显示的错误消息,“午餐失败。”。

$.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);
});

将显示的内容是:

“错误:内部服务器错误:{此处的完整堆栈}”

我想要的是:

“没吃午饭。”

4

1 回答 1

8

您可以解析responseText字符串,然后使用Message属性:

.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');
    }
});
于 2013-08-15T12:30:04.047 回答