How can I access the associated values of SwiftyDropbox errors? - ios

I’ve been working with SwiftyDropbox and I’m having a curious problem with errors. Specifically, I’m not sure how to manipulate errors in the closure callbacks provided after responses are received so that I can get at their associated values.
For instance, the completion handler for Dropbox.authorizedClient.filesListFolder provides a
CallError<(Files.ListFolderError)>?
to work with. How would I go about checking if it is a
CallError.HTTPError
, so that I can get the HTTP error code out of it? Right now I’m just sucking that information out of the error’s .description but that doesn’t seem like the right way to do it.
This is what I’ve tried. I suspect I’m failing to understand something with the generics involved.
client.filesListFolder(path: "", recursive: false).response({ (listFolderResult, listFolderError) -> Void in
switch listFolderError {
case let .HTTPError(code, message, requestId):
print("http error")
default:
print("not a http error")
}
Enum case 'HTTPError' not found in type 'CallError?'

The problem here is that we're trying to switch on an optional. This simpler example highlights the exact same problem:
enum Foo {
case a
case b
}
let x: Foo? = nil
switch x {
case .a:
print("a")
case .b:
print("b")
}
Enum case 'a' not found in type 'Foo?'
We can switch over optionals because Optional is itself an Enum, with two cases: None and Some(T).
So when we're switching over an optional, Swift expects some code like this:
switch someOptional {
case .Some(someValue):
print("do some things")
case .None:
print("someOptional was nil")
}
But that's probably not necessarily particularly useful to use. We have an optional enum, and ultimately, if we dealt with our optional in a switch, we'd just have nested switch statements. Instead, we should deal with our optional in the normal Swift way of dealing with optionals:
if let error = listFolderError {
switch error {
case let .HTTPError(code, message, requestID):
print("http error")
default:
print("some other error")
}
} else {
print("there was no error")
}

Related

Handling errors properly in swift

I am trying to learn swift and I have hit a wall... I want to be able to switch the type of error i get back so I can do different things. It works fine in the .success but not in the .failure
exporter.export(progressHandler: { (progress) in
print(progress)
}, completionHandler: { result in
switch result {
case .success(let status):
switch status {
case .completed:
break
default:
break
}
break
case .failure(let error):
// I want to check what the error is
// e.g. the debugger says its "cancelled"
break
}
})
}
Can somebody help me with this?
Thanks
If you just want to see what happened, print the error object's localizedDescription.
print(error.localizedDescription)
If you have a decision to make, cast to NSError and examine the domain and code. That is more reliable though not as user-friendly. Only actual testing will tell you what the possible values are.
let error = error as NSError
if error.domain == ... && error.code == ... {
You can work out the corresponding Swift Error type by looking in the FoundationErrors.h header file. Once you do, you can refine your case structure to filter the error type into its own case:
case .failure(let error as NextLevelSessionExporterError):
// do something
case .failure(let error):
// do something else

compare error object return by alamofire

I'm using Alamofire with EVReflection, in case responseObject fails to parse the raw response string into an object, an response.error will have some value, in case of a different error, a different value will be set.
Not sure how to compare those error values, to handle different error.
in case of JSON parsing error, print(error) will output
FAILURE: Error Domain=com.alamofirejsontoobjects.error Code=1 "Data could not be serialized. Input data was not json." UserInfo={NSLocalizedFailureReason=Data could not be serialized. Input data was not json.}
Alamofire.request(...)
.responseObject { (response: DataResponse<UserData>) in
guard response.error == nil else {
print(response.error)
return
}
}
When your request fails, you will get an error of type AFError from Alamofire. You can actually check AFError.swift file to get familiar with possible values. This file have really good documentation for every case.
Since AFError is an Error, which is of type enum, you can check like following:
switch err {
case .parameterEncodingFailed(let reason):
// do something with this.
// If you want to know more - check for reason's cases like
// switch reason {
// case .jsonEncodingFailed(let error):
// … // handle somehow
// case .propertyListEncodingFailed(let error):
// … // handle somehow
// }
case .responseValidationFailed(let reason):
// do something else with this
…
}
And for every reason you have some helper functions, so you can get even more info. Just check documentation.

Trying to print a description of an Error (AKA ErrorType) enum

I am using an enum that inherits from Error (or ErrorType in Swift 2) and I am trying to use it in such a way that I can catch the error and use something like print(error.description) to print a description of the error.
This is what my Error enum looks like:
enum UpdateError: Error {
case NoResults
case UpdateInProgress
case NoSubredditsEnabled
case SetWallpaperError
var description: String {
switch self {
case .NoResults:
return "No results were found with the current size & aspect ratio constraints."
case .UpdateInProgress:
return "A wallpaper update was already in progress."
case .NoSubredditsEnabled:
return "No subreddits are enabled."
case .SetWallpaperError:
return "There was an error setting the wallpaper."
}
}
// One of many nested enums
enum JsonDownloadError: Error {
case TimedOut
case Offline
case Unknown
var description: String {
switch self {
case .TimedOut:
return "The request for Reddit JSON data timed out."
case .Offline:
return "The request for Reddit JSON data failed because the network is offline."
case .Unknown:
return "The request for Reddit JSON data failed for an unknown reason."
}
}
}
// ...
}
An important thing to note is that there are a few nested enums within UpdateError so something like this won't work because the nested enums aren't of the UpdateError type themselves:
do {
try functionThatThrowsUpdateError()
} catch {
NSLog((error as! UpdateError).description)
}
Is there a better way of printing a description of the error without having to check every type of UpdateError that occurred in the catch statement?
You could define another (possibly empty) protocol, and conform your errors to it.
protocol DescriptiveError {
var description : String { get }
}
// specify the DescriptiveError protocol in each enum
You could then pattern match against the protocol type.
do {
try functionThatThrowsUpdateError()
} catch let error as DescriptiveError {
print(error.description)
}

Enum case switch not found in type

Can someone please help me with this.
I have the following public enum
public enum OfferViewRow {
case Candidates
case Expiration
case Description
case Timing
case Money
case Payment
}
And the following mutableProperty:
private let rows = MutableProperty<[OfferViewRow]>([OfferViewRow]())
In my init file I use some reactiveCocoa to set my MutableProperty:
rows <~ application.producer
.map { response in
if response?.application.status == .Applied {
return [.Candidates, .Description, .Timing, .Money, .Payment]
} else {
return [.Candidates, .Expiration, .Description, .Timing, .Money, .Payment]
}
}
But now the problem, when I try to get the value of my enum inside my rows it throws errors. Please look at the code below.
func cellViewModelForRowAtIndexPath(indexPath: NSIndexPath) -> ViewModel {
guard
let row = rows.value[indexPath.row],
let response = self.application.value
else {
fatalError("")
}
switch row {
case .Candidates:
// Do something
case .Expiration:
// Do something
case .Description:
// Do something
case .Timing:
// Do something
case .Money:
// Do something
case .Payment:
// Do something
}
}
It throws an error: Enum case 'some' not found in type 'OfferViewRow on the line let row = rows.value[indexPath.row]
And on every switch statements it throws: Enum case 'Candidates' not found in type '<<Error type>>
Can someone help me with this?
The guard statement wants an optional, as hinted by "Enum case 'some'" in the error message.
But rows.value[indexPath.row] is not Optional<OfferViewRow>, it is a raw OfferViewRow. So it won't enter a guard statement.
Move let row = rows.value[indexPath.row] one line up: Swift takes care of bounds checking, and will crash if indexPath.row is out of bounds.

Swift: Handling login error states properly?

I've been trying to find a better way to handle my error states.
Currently I have about 10 if else statements, which clearly is an inefficient way to handle my errors.
From what I've been able to find, it looks like enumerations are the way to go. But I havn't been able to implement it successfully.
Every example I've been able to find follow this form:
enum Result<T> {
case Success(T)
case Failure(String)
}
var result = divide(2.5, by:3)
switch result {
case Success(let quotient):
doSomethingWithResult(quotient)
case Failure(let errString):
println(errString)
}
But I don't quite see how this can work for my error states.
There's no if statements, not to mention explanation of where to implement these, and they all only have 1 "action" In the above example a println.
I have several lines of code I need to run for every error state.
Here's an example of my errorhandling for an email textfield.
if textField == emailTextField {
emailTextField.textColor = UIColor.formulaBlackColor()
emailIcon.setTitleColor(UIColor.formulaBlackColor(), forState: .Normal)
emailTextField.resignFirstResponder()
if textField.text.isEmpty {
emailIcon.setTitleColor(UIColor.formulaRedColor(), forState: .Normal)
emailState.text = ""
emailTextField.attributedPlaceholder = NSAttributedString(string:"Email Address",
attributes:[NSForegroundColorAttributeName: UIColor.formulaRedColor()])
showError("Please enter your email.")
} else if emailTextField.text.isValidEmail() == false {
emailIcon.setTitleColor(UIColor.formulaRedColor(), forState: .Normal)
emailTextField.textColor = UIColor.formulaRedColor()
emailState.text = ""
showError("Please enter a valid email address")
} else {
emailIcon.setTitleColor(UIColor.formulaBlackColor(), forState: .Normal)
emailState.textColor = UIColor.formulaGreenColor()
emailState.text = ""
hideError()
}
}
I've been trying to make an enum like this:
enum Login {
case NoInternetConnection
case NoEmail
case InvalidEmail
case NoPassword
case WrongEmailOrPassword
case Success
}
But I havn't found a way to make this work.
When I added a switch case, I was presented with an error "Expected Declaration",
I tried putting it in a function, and the error went away. But I havn't been able to figure out how to do anything with the cases.
switch Login {
case Success:println("CASE SUCCESS")
case NoEmail:println("CASE NoEmail")
}
Obviously I still have to implement my if statements in some way to check e.g. if the emailTextField is empty? But how can I set the case to NoEmail. And make it run several lines of code?
You need to have a value of that enumeration first, that you can check, like so:
enum Login {
case NoInternetConnection
case NoEmail
case InvalidEmail
case NoPassword
case WrongEmailOrPassword
case Success
}
// Here you get your result, e.g. from a function.
let loginResult = Login.Success
switch loginResult {
case let .NoInternetConnection:
println("No internet connection")
case let .NoEmail:
println("No email specified")
case let .InvalidEmail:
println("Email invalid")
case let .NoPassword:
println("No password specified")
case let .WrongEmailOrPassword:
println("Email or password wrong")
case let .Success:
println("Success")
}
Remember that there is also another way to go, which is Optional Chaining.
In my opinion, it is always best to break such conditional chains up into several functions (see also Clean Code), but unfortunately Swift does not support catching exceptions, so we have to go this way.

Resources