Honey Honey - 1 month ago 10
Swift Question

how to print error in catch

catch let error as LocksmithError{
print(error)// it would print the case of the error.
}


However if I do

catch LocksmithError.Duplicate{

}

catch{
print (LocksmithError) // Obviously I would just print LocksmithError, it won't print the case
print (LocksmithError.rawValue) // prints nothing
}


My question is: Using the 2nd approach is there any that I can actually retrieve and the value/case of the error? Or if I don't get the value right at the entry point ie the catch, then I miss the chance of doing it!

Answer

The catch blocks are exclusive cases, evaluated in order. When a match succeeds, we stop.

So, let's just think about this structure:

catch LocksmithError.Duplicate {
    // 1
    print("duplicate")
}
catch {
    // 2
    print(error)
}

If we are at 1, then what is in scope is the LocksmithError.Duplicate.

If we are at 2, then what is in scope is every other kind of error that gets caught. There's no way you can get hold of the LocksmithError.Duplicate here, because ex hypothesi it would have been caught in 1 and we wouldn't be here.

Now, the way I would do it is like this:

catch let err as LocksmithError {
    // 1
    print(err)
}
catch {
    // 2
    print(error)
}

That may be the sort of thing you are after; it gives us a value err that carries the error into the curly braces in 1. (The automatic error value exists only the final catch-all catch block.)

Comments