I'm trying to find an easier/more reliable way to figure out an NSError's localized description from its error code than Google searching it.
For example, I know that NSURLErrorDomain code -1003 corresponds to "A server with the specified hostname could not be found". But if I try to verify it in code it doesn't match.
let error = NSError(domain: "NSURLErrorDomain", code: -1003)
print(error.localizedDescription)
// "The operation couldn’t be completed. (NSURLErrorDomain error -1003.)"
Looking up -1003 in documentation also doesn't match: "The host name for a URL couldn’t be resolved."
So I am looking for a way to figure out descriptions from an error code with a function, or the documentation that has the description I expected. I was hoping there'd be a function similar to HTTPURLResponse.localizedString(forStatusCode:)
When you create your own NSError
object like that, that localizedDescription
is not generated for you. When URLSession
generates error objects, though, the localized description is populated:
let url = URL(string: "https://bad.domain")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error as? URLError {
print(error.localizedDescription) // “A server with the specified hostname could not be found.”
}
}.resume()
So, if you have an error and want to see the localized description, just do that. It simply will not work if you create your own NSError
object manually.
But generally, we wouldn't worry about the localized description and, instead, test for various code
values of URLError
, looking for a code
of .cannotFindHost
:
let url = URL(string: "https://bad.domain")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error as? URLError {
switch error.code {
case .cannotFindHost: print("cannotFindHost")
case .cancelled: print("cancelled")
case .badURL: print("badURL")
// ...
default: break
}
}
}.resume()
Or, alternatively, you can search for the old NSURLError
code values using NSError
, too, looking for NSURLErrorCannotFindHost
:
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error as NSError? {
switch error.code {
case NSURLErrorCannotFindHost: print("cannotFindHost")
case NSURLErrorCancelled: print("cancelled")
case NSURLErrorBadURL: print("badURL")
// ...
default: break
}
}
}.resume()
You can also “quick open” by pressing shift-command-O (the letter “Oh”), search for NSURLError
, uncheck the “Swift” button in the upper right corner of the quick open dialog:
When you open up the NSURLError.h
file, you can then see all the codes listed there.
But, no, just by creating a NSError
with the specified domain and code, the localizedDescription
isn't magically populated for you. URLSession
creates the proper error objects with descriptions, though.