【问题标题】:Custom error message with content-type response带有内容类型响应的自定义错误消息
【发布时间】:2017-08-12 19:16:14
【问题描述】:

我正在尝试在我的 MCV AngularJS 应用程序中实现一些错误处理,但遇到了一个我不确定如何解决的问题。

结构
在我的 AngularJS 服务 ticketService 我有以下方法:

this.downloadFile = function (fileId) {
    return $http.get(baseUrl + "/Downloadfile/" + fileId, { responseType: "blob" });
}

在我的控制器中:

$scope.downloadFile = function (fileId) {
    ticketService.downloadFile(fileId)
        .then(function (response) {
            // Handle correct request and response
        }, function (err) {
            // Handle error
            notify({ message: "Something went wrong: " + err.data.Message, position: "center", duration: 10000 });
        })
}

这是我从后端 MVC Web API 方法返回的内容:

var error = new HttpError("Failed to find file, bla bla bla.");
return Request.CreateResponse(HttpStatusCode.NotFound, error);

问题
我的问题是,由于我的responseType 设置为blob,我的err 对象是相同的响应类型。我相信我的后端服务应该可以覆盖此响应类型,并使用包含一些 Message 的对象进行响应。

从这个回复中,我以为我可以得到err.data.Message,但也许我误解了这个场景?

提前谢谢你。

【问题讨论】:

  • 你检查过 API 方法中的“HttpResponseMessage”吗?
  • 我不确定如何将自定义消息应用到 HttpResponseMessage 对象。只是内容上的吗?
  • @BasantaMatia HttpResponseMessage 给了我同样的问题。我的响应类型和对象仍然是Blob

标签: angularjs asp.net-web-api angularjs-http


【解决方案1】:
public HttpResponseMessage Get(int id)
    {
        try
        {
            return Request.CreateResponse(HttpStatusCode.OK, new { Status = 
                   "OK", Message = this._myContext.GetCustomer(id) });
        }
        catch(Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.Conflict, new { 
                   Status = "NO", Message = e.ToString() });
        }
    }

您可以返回任何消息,例如“找不到文件,bla bla bla”。在消息中。然后你只需要检查像 data.Message,

这样的 ajax 成功方法

【讨论】:

    【解决方案2】:

    $http 服务使用XHR API,它不能即时更改responseType

    您可以设置状态消息并使用它:

    public ActionResult Foo() 
    { 
        Response.StatusCode = 403;
        Response.StatusDescription = "Some custom message";
    
        return View(); // or Content(), Json(), etc
    }
    

    然后在 AngularJS 中:

    $scope.downloadFile = function (fileId) {
        return ticketService.downloadFile(fileId)
          .then(function (response) {
                // Handle correct request and response
                return response.data;
        }).catch(function (response) {
                // Handle error
                console.log(response.status);
                console.log(response.statusText);
                throw response;
        });
    };
    

    替代方法是:

    1. 使用Fetch API,它具有更强大、更灵活的功能集。
    2. 使用FileReader APIJSONparse() methodBlob 转换为JavaScript Object

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2021-06-08
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多