【问题标题】:How to get a custom error message from Web Api to jQuery.ajax?如何从 Web Api 到 jQuery.ajax 获取自定义错误消息?
【发布时间】:2013-08-17 15:08:12
【问题描述】:

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

如何获取自定义错误消息,由 CreateErrorResponse()HttpError 参数创建,由 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);
});

将显示的是:

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

我想要的是:

“没吃午饭。”

【问题讨论】:

  • 你的意思是“启动失败”而不是午餐
  • @KevinHolditch 我饿了!
  • 所以我现在已经阅读了你的问题:)

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


【解决方案1】:

您可以解析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');
    }
});

【讨论】:

  • 这就是我感到困惑的地方。 jqXhr.responseText.Message 有来自 InternalServerError 的错误消息(“发生错误。”),而不是我放入 HttpError 的自定义消息。
  • 我的回答有误。您应该使用alert(error.Message) 而不是alert(error).Message。 Message 属性将包含文本Failure to lunch.。我刚刚对其进行了测试,并且效果很好。你能显示jqXhr.responseText的值吗?
  • 事实证明,我很困惑,因为我的测试用例抛出了 another InternalServerError 异常,该异常是在我的 CreateErrorResponse 代码被命中之前返回的。在没有任何 try..catch 代码的情况下,Web API 将轻松应对此问题。你说的很对,Message 属性正是我所需要的。
猜你喜欢
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多