如何处理 Parse.com 将 HTTP 错误转换为 NSError?

How to handle Parse.com's transformation of a HTTP error to a NSError?

我正在从 Cloud Code 调用第 3 方服务器。前者可以 return 我想传递给调用 iOS 应用程序的 HTTP 错误。

我希望我的 iOS 应用能够在第 3 方服务器抛出 HTTP 异常时处理 HTTP 错误详细信息。

到目前为止,我发现的唯一方法是将这些异常视为云代码 "success"!

有没有更好的方法?

一个例子 当第 3 方服务器 return 出现 HTTP 400 时,"Missing Name" 错误:

我可以通过我的云代码调用:

response.error(httpResponse);

然后在 Swift 中,我可以用以下方法解析:

PFCloud.callFunctionInBackground("func", withParameters:[]) {
    (result, error) -> Void in
    if error == nil {
        // handle success
    } else {
        // handle error
        // Parse.com has wrapped the originating http error with a status code of 141 so I'll need to JSON parse the deeper fields to get 400 & "Missing Name".
    }

但是,我可以从 Cloud Code 调用 response.success(httpResponse) 然后执行此操作:

PFCloud.callFunctionInBackground("func", withParameters:[]) {
    (result, error) -> Void in
    if error == nil {
      let result = result as! [String:AnyObject]
      let status = result["status"]     
      let text = result["text"] as! String
      // status will be 400
      // text will be "Missing Name"
    } else {
       // handle Parse.com's 141s
    }

这使得字段解析更容易访问。但是我正在处理 HTTP 错误以及成功的调用。

您可以自定义错误 message/data,但遗憾的是,如果您使用 response.error() 方法,则无法更改错误代码 141。参见 this