gRPC Error Handling
#gRPC #Java
ステータスコードやエラーメッセージを扱う仕組みがある。protocol bufferでエラーメッセージを定義する必要はない。
サーバーサイド
StatusからErrorを選ぶ
エラーの種類: INTERNAL, NOT_FOUND, PERMISSION_DENIED, ...
withDescriptionでエラーの詳細をStringで記述
asException かasRuntimeExceptionでStatusExceptionかStatusRuntimeExceptionに変換
このときgRPCのMetadata として詳細(Trailer)を追加できる
StatusExceptionとStatusRuntimeExceptionに違いは無いが、APIは使い分けている。
Status in Exception form, for propagating Status information via exceptions. This is semantically equivalent to StatusRuntimeException, except for usage in APIs that promote checked exceptions. gRPC's stubs favor StatusRuntimeException. https://grpc.io/grpc-java/javadoc/io/grpc/StatusException.html
後者を使っておけば良さそう
クライアントサイド
try-catch でエラーを補足できる(Exception)
Status.fromThrowableでStatusを取得
Status.trailersFromThrowableでMetadataを取得
参考
公式
https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples/errorhandling
エラー  |  Cloud API  |  Google Cloud
GoogleのAPI設計ガイド
StatusをgRPC messageで定義している(内容は https://grpc.io/grpc-java/javadoc/io/grpc/Status.html と同じ)。すべてのRPCのレスポンスにStatusフィールドを含める使い方?
その他
Pattern for rich error handling in gRPC - Stack Overflow