Swift catching error - swift

Why is
if error = response.result.error else {
print (error)
}
Not allowed and throws an error within the function below? I would have expected it should go through well.
Alamofire.request(Router.RegisterUser(parameters))
.validate()
.responseJSON(completionHandler: { (response) -> Void in
if let receivedData = response.result.value {
let json = JSON(receivedData)
// Check for error in JSON
if let message = json["error"]["message"].string {
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: message)
print(error)
return
}
completionHandler(.Success(true), response: JSON(receivedData))
}
if error = response.result.error else {
print (error)
}
})
I use the validate function to avoid successful responses to the completionhandler, when indeed an error code is returned by the server. The problem now is, that the only error I can currently receive is the one, thrown by validate(). But I use error handling in my API as well and will return a suitable error message to the user.
Error Domain=com.alamofire.error Code=-6003 "Response status code was
unacceptable: 400" UserInfo={NSLocalizedFailureReason=Response status
code was unacceptable: 400}
How can I achieve this now? As by using validate, the response will never get processed as far as I understand?
Alamofire.request(Router.RegisterUser(parameters))
.validate()
.responseJSON(completionHandler: { (response) -> Void in
switch(response.result) {
case .Success(let response):
print(response)
case .Failure(let error):
print("FAILURE: \(error)")
}
})
}

There seems to be 2 issues in your code:
You are missing a let or guard to check if there is an error.
print(error) should be inside if as you are checking error is not nil and trying to print error in else which will be nil.

Related

Catch' block is unreachable but I included try

I'm getting the following error:
'catch' block is unreachable because no errors are thrown in 'do' block
But my try is present, how can I include the error then?
AF.request(url).responseData(completionHandler: { data in
do {
if let apiJsonData = try? JSONDecoder().decode(MyModel.self, from: data.data!){
self.items = apiJsonData.data.items
}
} catch {
print("Decoding failed -> ERROR:", error)
}
}
If I include it in the header like: data, error in it throws an error:
Contextual closure type '(AFDataResponse<Data>) -> Void' (aka '(DataResponse<Data, AFError>) -> ()') expects 1 argument, but 2 were used in closure body
How can I have the try catch correctly setup?
You've used try?, not try.
try? turns the whole expression into nil if an error was thrown. It already handles the error on its own, so there's no more error for the catch block to catch. On the other hand, try doesn't do that. For more info, see the Error handling section of the Swift Guide.
If you want the error to be caught by the catch block, you should use try, and delete the if block.
AF.request(url).responseData(completionHandler: { data in
do {
let apiJsonData = try JSONDecoder().decode(MyModel.self, from: data.data!)
self.items = apiJsonData.data.items
} catch {
print("Decoding failed -> ERROR:", error)
}
}
Also note that you are assuming data.data is not nil here. This might not be the case if the network request fails. Better check for it:
AF.request(url).responseData(completionHandler: { data in
do {
guard let data = data.data else {
print("Response Error:", data.error)
return
}
let apiJsonData = try JSONDecoder().decode(MyModel.self, from: data.data!)
self.items = apiJsonData.data.items
} catch {
print("Decoding failed -> ERROR:", error)
}
}

cast server response in AFError

What I'm trying to achieve is that I have a NetworkManager that handles the request's to the server, and handle the error through AFError.
However sometimes when the server response is 4xx, there is a custom message with that response which I want to show that to the user But don't know how to implement it.
This is my NetworkManager
static let shared:NetworkManager = {
return NetworkManager()
}()
typealias completionHandler = ((Result<Data, AFError>) ->Void)
func handleAFrequest(request: DataRequest,completion: #escaping completionHandler) {
request.validate(statusCode: 200..<300)
request.responseJSON { (response) in
switch response.result {
case .success(_):
if let data = response.data {
completion(.success(data))
}
case .failure(let error):
print(error.localizedDescription)
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
completion(.failure(.invalidURL(url: URL)))
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription); Reason:\(reason)")
completion(.failure(.responseValidationFailed(reason: reason)))
I want to be able to cast server response in addition to the error, and show Message of the response to the user.
Server Response example when StatusCode is 4xx:
{
"data":
"code":401;
"Message":"Phone Invalid"
}
I have parsed api errors in many of my projects. I believe there is a better alternative to handle the showing or errors if any, to the user. Please see my code, in it, if there is a error I show it in a toast. Showing in a toast is the not focal point but you can see how I handle the error case in my code and it has never failed. Please change the params accordingly to your api call
func postMethod(mylist: [String:Any]) {
print(K.APIUrl)
print(K.port)
AF.request("\(K.urlFromUrlField!):\(K.configPort)/snhttp-01?", method: .put, parameters: mylist)
.authenticate(username: username, password: password)
.response { response in
switch response.result {
case .success:
print("\nValidation Successful from put method")
print(response.result)
print(response.value as Any)
//get xml code and error msg if any
if let response = response.data{
let xml = XML.parse(response)
print(xml)
print("\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")" )
let code = xml.Response.Code.text ?? "No code value in response"
let responseMessage = xml.Response.Message.text ?? "No message returned from server"
print("\nCode value from server: \(code)")
print("\nResponse message from server: \(responseMessage)")
}
else{
print("\nSuccess block: Request Successfully sent, BUT there was nothing from the server to unwrap! / nothing sent back from the server\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")")
}
case let .failure(error):
if let response = response.data {
let xml = XML.parse(response)
let code = xml.Response.Code.text ?? "\nNo code value in response"
let responseMessage = xml.Response.Message.text ?? "No message returned from server"
print("\nCode value from server: \(code)")
print("\nResponse message from server: \(responseMessage)")
print(error)
}
else {
print("\nFailure Block: A connection to the server could not be established")
}
}}
}
This code parses the xml from the api. However you can discard that and just focus on how I handle the response and consequently the error.
This is the solution that works for me.
All you need to do is create a custom error type:
struct APIError: Error, Decodable {
let status: Int?
let message: String?
let key: String?
}
Then call Alamofire, which will return an AFDataResponse which you can parse:
func performRequest<T: Decodable>(route: APIRouter, completion: #escaping (APIResponse<T>) -> Void) {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
AF.request(route)
.validate()
.responseDecodable(decoder: decoder, emptyResponseCodes: [200, 201]) { (response: AFDataResponse<T>) in
self.parseResponse(response: response, completion: completion)
}
}
Parsing is done like this:
private func parseResponse<T: Decodable>(response: AFDataResponse<T>, completion: #escaping (APIResponse<T>) -> Void) {
switch response.result {
case .success(let data):
completion(APIResponse<T>.success(data))
case .failure(let error):
if let data = response.data,
// THIS IS WHERE YOU CAST AFError TO YOUR CUSTOM APIError
let apiError = try? JSONDecoder().decode(APIError.self, from: data) {
completion(APIResponse.failure(apiError))
} else {
completion(APIResponse.failure(error))
}
}
}
Hope this helps!

Alamofire and PromiseKit returning a Promise<[T]>

I used Alamofire and PromiseKit as separate Cocoapod installs. I can retrieve the JSON data using Alamofire, but I am receiving the error below when configuring PromiseKit. The error below appears in the line where 'fulfill, reject' are in.
Error message: Contextual closure type '(Resolver<_>) -> Void' expects 1 argument, but 2 were used in closure body
I am using Xcode 9.2 and IOS 11.2 inside of the Simulator. Thank you for your advice in advance!
func wantToReturnAnArrayOfActor() -> Promise<[Actor]> {
return Promise { fulfill, reject in
Alamofire.request(ApiUrl.url.rawValue).responseJSON { (response) in
switch(response.result)
{
case .success(let responseString): print("my response string = \(responseString)")
let actorResponse = ActorApiResponse(JSONString: "\(responseString)")//converts all of the data into the ActorApiResponse model class
return when(fulfilled: actorResponse)
DispatchQueue.main.async {
print("actorResponse = \(String(describing: actorResponse))")
}
case .failure(let error): print("alamofire error = \(error)")
}
}
}
}
Should it rather be like this,
func wantToReturnAnArrayOfActor() -> Promise<[Actor]> {
return Promise() { resolver in
Alamofire.request(ApiUrl.url.rawValue).responseJSON { (response) in
switch(response.result)
{
case .success(let responseObject):
let actorResponse = ActorApiResponse(jsonObject: responseObject)
let actors = actorResponse.getActors()
resolver.fulfill(actors)
case .failure(let error):
resolver.reject(error)
}
}
}
}
The initializer closure for Promise takes in single argument, which is of type Resolver, which is what your error says. Then, you would want to resolve your promise with result which is of type [Actor] when the promise execution is finished or then reject with error if error occurred during the execution.
Few points to note here:
Alamofire.request(_).responseJSON returns json object not json string.
If your ActorApiResponse is the object which transforms the json to [Actor], you should have proper method to convert json object to actual data type ie. [Actor].
You could have your ActorApiResponse something like this,
struct ActorApiResponse {
init(jsonObject: Any) {
}
func getActors() -> [Actor] {
// calculate and return actors
return []
}
}
Then, you can call it from else where,
wantToReturnAnArrayOfActor().done {
// do something with [Actor here]
// You can also chain the multiple promise using .then instead of using done
}.catch { error in
print("Error occurred \(error)")
}

Best way to handle errors from async closures in Swift 2?

I'm using a lot of async network request (btw any network request in iOS need to by async) and I'm finding way to better handle errors from Apple's dataTaskWithRequest which not supports throws.
I have code like that:
func sendRequest(someData: MyCustomClass?, completion: (response: NSData?) -> ()) {
let request = NSURLRequest(URL: NSURL(string: "http://google.com")!)
if someData == nil {
// throw my custom error
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
// here I want to handle Apple's error
}
task.resume()
}
I need to parse my possible custom errors and handle possible connection errors from dataTaskWithRequest. Swift 2 introduced throws, but you can't throw from Apple's closure because they have no throw support and running async.
I see only way to add to my completion block NSError returning, but as I know using NSError is old-style Objective-C way. ErrorType can be used only with throws (afaik).
What's the best and most modern method to handle error when using Apple network closures? There is no way no use throws in any async network functions as I understand?
there are many ways you can solve this, but i would recommend using a completion block which expects a Result Enum. this would probably be the most 'Swift' way.
the result enum has exactly two states, success and error, which a big advantage to the usual two optional return values (data and error) which lead to 4 possible states.
enum Result<T> {
case Success(T)
case Error(String, Int)
}
Using the result enum in a completion block finishes the puzzle.
let InvalidURLCode = 999
let NoDataCode = 998
func getFrom(urlString: String, completion:Result<NSData> -> Void) {
// make sure the URL is valid, if not return custom error
guard let url = NSURL(string: urlString) else { return completion(.Error("Invalid URL", InvalidURLCode)) }
let request = NSURLRequest(URL: url)
NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
// if error returned, extract message and code then pass as Result enum
guard error == nil else { return completion(.Error(error!.localizedDescription, error!.code)) }
// if no data is returned, return custom error
guard let data = data else { return completion(.Error("No data returned", NoDataCode)) }
// return success
completion(.Success(data))
}.resume()
}
because the return value is a enum, you should switch off of it.
getFrom("http://www.google.com") { result in
switch result {
case .Success(let data):
// handle successful data response here
let responseString = String(data:data, encoding: NSASCIIStringEncoding)
print("got data: \(responseString)");
case .Error(let msg, let code):
// handle error here
print("Error [\(code)]: \(msg)")
}
}
another solution would be to pass two completion blocks, one for success and one for error. something along the lines of:
func getFrom(urlString: String, successHandler:NSData -> Void, errorHandler:(String, Int) -> Void)
It's very similar to Casey's answer,
but with Swift 5, now we have Result (generic enumeration) implementation in standard library,
//Don't add this code to your project, this has already been implemented
//in standard library.
public enum Result<Success, Failure: Error> {
case success(Success), failure(Failure)
}
It's very easy to use,
URLSession.shared.dataTask(with: url) { (result: Result<(response: URLResponse, data: Data), Error>) in
switch result {
case let .success(success):
handleResponse(success.response, data: success.data)
case let .error(error):
handleError(error)
}
}
https://developer.apple.com/documentation/swift/result
https://github.com/apple/swift-evolution/blob/master/proposals/0235-add-result.md
There's an elegant approach utilising a JavaScript-like Promise library or a Scala-like "Future and Promise" library.
Using Scala-style futures and promises, it may look as follows:
Your original function
func sendRequest(someData: MyCustomClass?, completion: (response: NSData?) -> ())
may be implemented as shown below. It also shows, how to create a promise, return early with a failed future and how to fulfill/reject a promise:
func sendRequest(someData: MyCustomClass) -> Future<NSData> {
guard let url = ... else {
return Future.failure(MySessionError.InvalidURL) // bail out early with a completed future
}
let request = ... // setup request
let promise = Promise<NSData>()
NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard let error = error else {
promise.reject(error) // Client error
}
// The following assertions should be true, unless error != nil
assert(data != nil)
assert(response != nil)
// We expect HTTP protocol:
guard let response = response! as NSHTTPURLResponse else {
promise.reject(MySessionError.ProtocolError) // signal that we expected HTTP.
}
// Check status code:
guard myValidStatusCodeArray.contains(response.statusCode) else {
let message: String? = ... // convert the response data to a string, if any and if possible
promise.reject(MySessionError.InvalidStatusCode(statusCode: response.statusCode, message: message ?? ""))
}
// Check MIME type if given:
if let mimeType = response.MIMEType {
guard myValidMIMETypesArray.contains(mimeType) else {
promise.reject(MySessionError.MIMETypeNotAccepted(mimeType: mimeType))
}
} else {
// If we require a MIMEType - reject the promise.
}
// transform data to some other object if desired, can be done in a later, too.
promise.fulfill(data!)
}.resume()
return promise.future!
}
You might expect a JSON as response - if the request succeeds.
Now, you could use it as follows:
sendRequest(myObject).map { data in
return try NSJSONSerialization.dataWithJSONObject(data, options: [])
}
.map { object in
// the object returned from the step above, unless it failed.
// Now, "process" the object:
...
// You may throw an error if something goes wrong:
if failed {
throw MyError.Failed
}
}
.onFailure { error in
// We reach here IFF an error occurred in any of the
// previous tasks.
// error is of type ErrorType.
print("Error: \(error)")
}

Swift Alamofire: How to get the HTTP response status code

I would like to retrieve the HTTP response status code (e.g. 400, 401, 403, 503, etc) for request failures (and ideally for successes too). In this code, I am performing user authentication with HTTP Basic and want to be able to message the user that authentication failed when the user mistypes their password.
Alamofire.request(.GET, "https://host.com/a/path").authenticate(user: "user", password: "typo")
.responseString { (req, res, data, error) in
if error != nil {
println("STRING Error:: error:\(error)")
println(" req:\(req)")
println(" res:\(res)")
println(" data:\(data)")
return
}
println("SUCCESS for String")
}
.responseJSON { (req, res, data, error) in
if error != nil {
println("JSON Error:: error:\(error)")
println(" req:\(req)")
println(" res:\(res)")
println(" data:\(data)")
return
}
println("SUCCESS for JSON")
}
Unfortunately, the error produced does not seem to indicate that an HTTP status code 409 was actually received:
STRING Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
res:nil
data:Optional("")
JSON Error:: error:Optional(Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo=0x7f9beb8efce0 {NSErrorFailingURLKey=https://host.com/a/path, NSLocalizedDescription=cancelled, NSErrorFailingURLStringKey=https://host.com/a/path})
req:<NSMutableURLRequest: 0x7f9beb89d5e0> { URL: https://host.com/a/path }
res:nil
data:nil
Additionally, it would be nice to retrieve the HTTP body when an error occurs because my server-side will put a textual description of the error there.
Questions
Is it possible to retrieve the status code upon a non-2xx response?
Is it possible to retrieve the specific status code upon a 2xx response?
Is it possible to retrieve the HTTP body upon a non-2xx response?
Thanks!
For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 4.0 / Alamofire >= 5.0
response.response?.statusCode
More verbose example:
Alamofire.request(urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
var statusCode = response.response?.statusCode
if let error = response.result.error as? AFError {
statusCode = error._code // statusCode private
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
case .parameterEncodingFailed(let reason):
print("Parameter encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .multipartEncodingFailed(let reason):
print("Multipart encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
switch reason {
case .dataFileNil, .dataFileReadFailed:
print("Downloaded file could not be read")
case .missingContentType(let acceptableContentTypes):
print("Content Type Missing: \(acceptableContentTypes)")
case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
case .unacceptableStatusCode(let code):
print("Response status code was unacceptable: \(code)")
statusCode = code
}
case .responseSerializationFailed(let reason):
print("Response serialization failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
// statusCode = 3840 ???? maybe..
default:break
}
print("Underlying error: \(error.underlyingError)")
} else if let error = response.result.error as? URLError {
print("URLError occurred: \(error)")
} else {
print("Unknown error: \(response.result.error)")
}
print(statusCode) // the status code
}
(Alamofire 4 contains a completely new error system, look here for details)
For Swift 2.x users with Alamofire >= 3.0
Alamofire.request(.GET, urlString)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
if let alamoError = response.result.error {
let alamoCode = alamoError.code
let statusCode = (response.response?.statusCode)!
} else { //no errors
let statusCode = (response.response?.statusCode)! //example : 200
}
}
In the completion handler with argument response below I find the http status code is in response.response.statusCode:
Alamofire.request(.POST, urlString, parameters: parameters)
.responseJSON(completionHandler: {response in
switch(response.result) {
case .Success(let JSON):
// Yeah! Hand response
case .Failure(let error):
let message : String
if let httpStatusCode = response.response?.statusCode {
switch(httpStatusCode) {
case 400:
message = "Username or password not provided."
case 401:
message = "Incorrect password for user '\(name)'."
...
}
} else {
message = error.localizedDescription
}
// display alert with error message
}
Alamofire
.request(.GET, "REQUEST_URL", parameters: parms, headers: headers)
.validate(statusCode: 200..<300)
.responseJSON{ response in
switch response.result{
case .Success:
if let JSON = response.result.value
{
}
case .Failure(let error):
}
Best way to get the status code using alamofire.
Alamofire.request(URL).responseJSON {
response in
let status = response.response?.statusCode
print("STATUS \(status)")
}
Or use pattern matching
if let error = response.result.error as? AFError {
if case .responseValidationFailed(.unacceptableStatusCode(let code)) = error {
print(code)
}
}
you may check the following code for status code handler by alamofire
let request = URLRequest(url: URL(string:"url string")!)
Alamofire.request(request).validate(statusCode: 200..<300).responseJSON { (response) in
switch response.result {
case .success(let data as [String:Any]):
completion(true,data)
case .failure(let err):
print(err.localizedDescription)
completion(false,err)
default:
completion(false,nil)
}
}
if status code is not validate it will be enter the failure in switch case
In your responseJSON completion, you can get the status code from the response object, which has a type of NSHTTPURLResponse?:
if let response = res {
var statusCode = response.statusCode
}
This will work regardless of whether the status code is in the error range. For more information, take a look at the NSHTTPURLResponse documentation.
For your other question, you can use the responseString function to get the raw response body. You can add this in addition to responseJSON and both will be called.
.responseJson { (req, res, json, error) in
// existing code
}
.responseString { (_, _, body, _) in
// body is a String? containing the response body
}
Your error indicates that the operation is being cancelled for some reason. I'd need more details to understand why. But I think the bigger issue may be that since your endpoint https://host.com/a/path is bogus, there is no real server response to report, and hence you're seeing nil.
If you hit up a valid endpoint that serves up a proper response, you should see a non-nil value for res (using the techniques Sam mentions) in the form of a NSURLHTTPResponse object with properties like statusCode, etc.
Also, just to be clear, error is of type NSError. It tells you why the network request failed. The status code of the failure on the server side is actually a part of the response.
Hope that helps answer your main question.
I needed to know how to get the actual error code number.
I inherited a project from someone else and I had to get the error codes from a .catch clause that they had previously setup for Alamofire:
} .catch { (error) in
guard let error = error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
}
Or if you need to get it from the response value follow #mbryzinski's answer
Alamofire ... { (response) in
guard let error = response.result.error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
})
For Swift 2.0 users with Alamofire > 2.0
Alamofire.request(.GET, url)
.responseString { _, response, result in
if response?.statusCode == 200{
//Do something with result
}
}
For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 5.0
Used request modifier to increase and decrease the timeout interval.
Alamofire's request creation methods offer the most common parameters for customization but sometimes those just aren't enough. The URLRequests created from the passed values can be modified by using a RequestModifier closure when creating requests. For example, to set the URLRequest's timeoutInterval to 120 seconds, modify the request in the closure.
var manager = Session.default
manager.request(urlString, method: method, parameters: dict, headers: headers, requestModifier: { $0.timeoutInterval = 120 }).validate().responseJSON { response in
OR
RequestModifiers also work with trailing closure syntax.
var manager = Session.default
manager.request("https://httpbin.org/get") { urlRequest in
urlRequest.timeoutInterval = 60
urlRequest.allowsConstrainedNetworkAccess = false
}
.response(...)
AF.request(url, method: .get).responseDecodable(of: Weather.self) { response in
switch response.result {
case .success(let data):
print(data)
var statusCode = response.response?.statusCode
if statusCode == 200 {
print(response)
}
case .failure(let error):
print(error)
}
}