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

时间:2015-12-07 12:07:53

标签: alamofire

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

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

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

{“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)

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

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

4 个答案:

答案 0 :(得分:18)

根据Alamofire 3.0 migration guide的.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.
     }
  }
}

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

另一个清洁选项可能是写Custom Response Serializer

答案 1 :(得分: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))
        }
   }

答案 2 :(得分:4)

我使用以下几行来阅读Alamofire请求中的响应正文。

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


    }

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

最好的问候

答案 3 :(得分:0)

对于Alamofire 4.0及更高版本:

尝试一下 response.response?.statusCode

url:“您的URL”

参数:“您的参数字典”

标题:“您的标题字典”

我正在使用SwiftyJSON进行JSON解析

  

一个示例请求在这里:

class Club < ApplicationRecord
   has_many :memberships, :dependent => :destroy 
   has_many :users, :through => :memberships
   accepts_nested_attributes_for :membership 
end

class User < ApplicationRecord
   has_many :memberships, :dependent => :destroy 
   has_many :clubs, :through => :memberships
   accepts_nested_attributes_for :membership 
end

class Membership < ApplicationRecord
    require 'csv'
    belongs_to :club
    belongs_to :user
    accepts_nested_attributes_for :club
end
相关问题