2017-03-21 75 views
0

我试图在我的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,但也许我误解了这种情况?

预先感谢您。

+0

你用API方法检查“HttpResponseMessage”吗? –

+0

我不知道如何将自定义消息应用于'HttpResponseMessage'对象。这只是内容? – Detilium

+0

@BasantaMatia'HttpResponseMessage'给了我同样的问题。仍然我的响应类型和对象的类型是'Blob' – Detilium

回答

0
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

+0

因此,这不会打我的错误回调? – Detilium

0

的$ 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