从错误中获取服务器响应消息

tom*_*mpa 9 alamofire

我的服务器(CakePHP)响应如下:

$this->response->statusCode('400');
$this->response->type('json');
$this->response->body(json_encode(array('message' => 'Bookmark already exists')));
Run Code Online (Sandbox Code Playgroud)

邮差输出看起来像你期望的那样:

{"message":"书签已存在"}

问题是我找不到从失败处理程序访问此消息的方法(Alamofire 3.1.3 + SwiftyJSON 2.3.2)

Alamofire.request(.POST...
.validate()
.responseJSON { response in

switch response.result {

case .Success(_):                           
// All good

case .Failure(let error):
// Status code 400                 
print(response.request)  // original URL request
print(response.response) // URL response
print(response.data)     // server data
print(response.result)
Run Code Online (Sandbox Code Playgroud)

我找不到一种方法将response.data转换为JSON,因为我只是得到nil,结果只返回FAILURE.

有没有办法从故障处理程序访问此服务器消息?

小智 19

根据Alamofire 3.0迁移指南,未在.Failure案例中解析数据.但是,服务器数据仍然可以在response.data中使用,并且可以进行解析.

下面应该可以手动解析:

Alamofire.request(.POST, "https://example.com/create", parameters: ["foo": "bar"])
  .validate()
  .responseJSON { response in
     switch response.result {
     case .Success:
         print("Validation Successful")
     case .Failure(_):
          var errorMessage = "General error message"

          if let data = response.data {
            let responseJSON = JSON(data: data)

            if let message: String = responseJSON["message"].stringValue {
              if !message.isEmpty {
                errorMessage = message
              }
            }
          }

          print(errorMessage) //Contains General error message or specific.
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

这使用SwiftyJSON,它提供转换NSData的JSON结构.解析NSData到JSON可以在没有SwiftyJSON的情况下完成,在这里回答.

另一个清洁选项可能是编写自定义响应序列化程序.


Sof*_*ner 6

路由器没有SwiftyJSON的方法:

Alamofire.request(APIRouter.Register(params: params)).validate().responseJSON { response in
    switch response.result {
        case .Success(let json):
            let message = json["clientMessage"] as? String
            completion(.Success(message ?? "Success"))
        case .Failure(let error):
            var errorString: String?

            if let data = response.data {
               if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) as! [String: String] {
                   errorString = json["error"]
               }
            }

            completion(.Error(errorString ?? error.localizedDescription))
        }
   }
Run Code Online (Sandbox Code Playgroud)


BHu*_*lse 5

我使用以下几行从Alamofire请求中读取响应正文。

    Alamofire.request(.POST, serveraddress, headers: headers, encoding: .JSON)
        .response{ request, response, data, error in
            let responseData = String(data: data!, encoding: NSUTF8StringEncoding)
            print(responseData)


    }
Run Code Online (Sandbox Code Playgroud)

有了这个主体,我可以获得我的自定义服务器响应错误消息。

最好的祝福