How do you get the error code from an error?

Hi,


Getting the error code from an error protocol would seem to be an important capability, but as a swift newbie I can't figure it out. I'd appreciate some wisdom on how this works.


The specific situation is this:


When using the ios Speech library SFSpeechRecognizer framework I want to specially handle some errors from the recognitionTask. The problem is I can't figure out how to extract the error code. I've looked all around and I couldn't find an example or explanation in the doc on how to get at it.


The signature:

func recognitionTask(with request: SFSpeechRecognitionRequest, resultHandler: @escaping (SFSpeechRecognitionResult?, Error?) -> Void) -> SFSpeechRecognitionTask


Drilling down on Error says it's "protocol Error" which doesn't help very much.


When there is an error the local description show's there's a code:

2018-10-20 12:33:49.037515-0700 readsay[55123:12025377] error: Optional(Error Domain=kAFAssistantErrorDomain Code=209 "(null)")


The problem is on inspection the error doesn't seem to contain anything recognizable as an error code. There are option for flatMap, map, localDescription, debugDescription, mirror, unsafelyWrapped.


My Swift is not very swift. Can anyone please explain how to get to the error parameters?


Or if that's not how errors should be handled, to better handle errors.



thanks

When you call the recognitionTask, you have a resultHandler in the arguments:


So call

let speechRecognition = speechRecognizer?. recognitionTask(with: myRequest,
          resultHandler: { (result, error) in
                    if (error != nil) {
                         print("fails with error: \(error!.localizedDescription)")
                    }
          }
     )

or get the error to proceed.


They deal with a situation close to yours here:

https://stackoverflow.com/questions/44767316/ios-speech-recognition-error-domain-kafassistanterrordomain-code-216-null

You should better show your code you have tried.

Error domains and codes are a feature of

NSError
. If you’re calling a system framework and want to look for a specific error code, you can convert the
Error
value to an
NSError
and then get the
domain
and
code
properties from that. For example:
// assuming `error` is an `Error?`
if let error = error as NSError? {
    NSLog("error %@ / %d", error.domain, error.code)
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
How do you get the error code from an error?
 
 
Q