~ If you don't use the low-level C++ FIDL bindings you may stop reading now ~
TLDR: Avoiding switch case on the fidl::Reason enum, prefer one of the more readable accessors instead.
Most LLCPP result/error objects provide a way to access the underlying reason, a fidl::Reason, describing the cause. However, there are some downsides:
fidl::Reason is an enum with lots of members, some of which have subtle meanings. We have seen code that misunderstood particular enums and wrote incorrect handling. They were hard to catch because testing for error conditions exhaustively is tricky.
Having an enum is challenging for future extensions because users might try to exhaustively match on the members (example in tree). If we add new kinds of reasons, those switch-case would be broken either at compile time or silently at runtime, because they were not prepared for that extra member.
To address those shortcomings, we now provide boolean-returning accessors that help determine if the error is of a particular kind, instead of always exhaustively switching on all potential reasons:
bool is_peer_closed(): whether the operation failed/bindings unbound because the peer closed their endpoint.
bool is_canceled(): whether the operation failed because it was canceled.
bool is_user_initiated(): whether the server unbinding was initiated by the user via one of completer.Close(...) or binding_ref.Unbind() or similar, rather than due to some terminal error.
And many more… See the documentation on fidl::UnbindInfo and fidl::Result.
What's changed:
While one could still reach for the underlying enum and write switch case if they really need it, it is now discouraged. When writing a switch case on the enum, make sure to add a default: case.
Consider if some of the above accessors lead to simpler error handling code than switching on the reason. Here's an example showing before/after using the accessors:
The accessors work in regular FIDL call results too:
Please let us know on fidl...@fuchsia.dev if you have questions or suggestions. Thanks.
Cheers, Yifei