Get server response message from error

My server (CakePHP) responds like this:

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

Postman's output looks like you expected:

{"message": "Bookmark already exists"}

The problem is that I cannot find a way to access this message from the failure handler (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) 

I cannot find a way to drop the response.data for JSON as I just get nil and the result returns only FAILURE.

Is there a way to access this server message from a failure handler?

+5
source share
3 answers

Data is not analyzed in the case of .Failure in the Alamofire 3.0 manual. However, server data is still available in the response.data file and can be analyzed.

The following should be analyzed manually:

 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. } } } 

This uses SwiftyJSON , which provides a JSON structure for converting NSData. NSData parsing for JSON can be done without SwiftyJSON, answered here .

Another cleaning option might be a Custom Response Serializer entry.

+12
source

Method with a router and without 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)) } } 
+4
source

I used the following lines to read the response body from an Alamofire request.

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

With this body, I can get a custom server response error.

Best wishes

+3
source

Source: https://habr.com/ru/post/1237572/


All Articles