如何从Web Api获取自定义错误消息到jQuery.ajax?

时间:2013-08-15 12:19:50

标签: c# jquery asp.net-web-api httpresponse jqxhr

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

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

在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);
});

将显示的内容是:

  

“错误:内部服务器错误:{full stack here}”

我想要的是:

  

“午餐不吃。”

1 个答案:

答案 0 :(得分: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');
    }
});