Designing gRPC Services: Error Handling Best Practices

In REST, we use HTTP Status Codes (404, 500). In gRPC, we must use `RpcException` and `Status` objects to communicate errors rich in metadata across service boundaries.

Standard Status Codes

  • StatusCode.NotFound -> Entity missing.
  • StatusCode.InvalidArgument -> Validation failed.
  • StatusCode.FailedPrecondition -> ETag mismatch / Conflict.

Interceptor for Global Error Handling

public class ExceptionInterceptor : Interceptor
{
    public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(...)
    {
        try
        {
            return await continuation(request, context);
        }
        catch (DbUpdateConcurrencyException)
        {
            throw new RpcException(new Status(StatusCode.Aborted, "Concurrency conflict"));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Crash");
            throw new RpcException(new Status(StatusCode.Internal, "Internal Server Error"));
        }
    }
}

Key Takeaways

  • Never expose internal stack traces in RpcExceptions.
  • Use the `Trailers` collection to send detailed validation error lists.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.