how to print error in catch

2019-02-20 15:38发布

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!

1条回答
做个烂人
2楼-- · 2019-02-20 15:47

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.)

查看更多
登录 后发表回答