Skip to Content
Course content

201: Error Handling in gRPC Services

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're at a high-end restaurant. You order the sea bass, but a few minutes later, the waiter comes back. If the waiter just says, "There was a problem," and walks away, you're left wondering: Is the kitchen closed? Did they run out of fish? Did the chef just drop your plate? You can't make an informed decision on what to do next because the feedback was generic.

Now, imagine the waiter says, "I'm sorry, we're actually out of sea bass" (that's a Not Found error). You can immediately pivot and order the salmon. Or, if they say, "The kitchen is currently dealing with a grease fire" (that's an Internal Server Error), you know it's not your fault, and you might just leave the restaurant entirely. The type of error tells you exactly how to react.

In gRPC, if you just let a Ruby exception bubble up, the client gets a generic "Internal Server Error." You've basically become the waiter who just says "there was a problem." To build a professional service, you have to map your internal Ruby logic to specific gRPC status codes so your clients know whether to retry the request or stop and fix their input.

Translating Ruby Exceptions to gRPC Statuses

In a standard Ruby app, you might raise a CustomNotFoundError. But a gRPC client (which might be written in Go or Python) doesn't know what that is. We need to use GRPC::BadStatus or its specialized subclasses. I've found that the cleanest way to handle this is to wrap your business logic in a rescue block and "translate" the error right at the service boundary.

# Let's look at a Stock Management service
class InventoryService < Inventory::Service::Service
  def deduct_stock(call)
    item_id = call.request.item_id
    amount = call.request.amount

    # Imagine this method raises our own custom business exceptions
    Warehouse.deduct!(item_id, amount) 
    
    Inventory::DeductResponse.new(success: true)
  rescue Warehouse::ItemNotFound => e
    # This is our "Out of sea bass" scenario
    fail GRPC::NotFound.new(e.message)
  rescue Warehouse::InsufficientStock => e
    # The item exists, but the request is invalid for the current state
    fail GRPC::FailedPrecondition.new(e.message)
  rescue StandardError => e
    # The "Kitchen fire" - something went wrong that we didn't anticipate
    # Log this properly! Don't just swallow it.
    puts "Unexpected error: #{e.message}" 
    fail GRPC::Internal.new("An unexpected error occurred on the server")
  end
end

Choosing the Right Status Code

I see a lot of developers default to Internal for everything. Don't do that. It makes debugging a nightmare for the person calling your API. Here is how I usually decide which one to use:

  • GRPC::InvalidArgument: The client sent something wrong. A negative number for stock, or a malformed ID. The client should not retry this without changing the request.
  • GRPC::NotFound: The resource doesn't exist. This is a "hard" failure for that specific ID.
  • GRPC::FailedPrecondition: The request is technically valid, but the system isn't in a state to do it. For example, trying to ship an order that's already been cancelled.
  • GRPC::Unavailable: The service is overloaded or shutting down. This is a signal to the client that they should try again in a few seconds.

Adding Context Beyond the Status

Sometimes a status code and a string message aren't enough. You might want to tell the client exactly how many items are left in stock when a FailedPrecondition occurs. In Ruby, you can pass metadata in the error. While gRPC doesn't have a "body" for errors like REST does, you can use the metadata hash to send back key-value pairs.

Just remember: keep this metadata small. It's sent in the headers, and bloating it can impact performance. I usually only put a correlation ID or a specific error code there, leaving the detailed human-readable message for the status message itself.




📋 Practical Task

Refactoring the Broken Payment Gateway

You've inherited a PaymentService that is currently "leaking" Ruby exceptions. When a user has insufficient funds, the server crashes with a RuntimeError, and the client just sees a generic INTERNAL error. This is causing the frontend team to show a "System Crash" message to users instead of a "Please add funds" message.

Your Goal: Refactor the process_payment method below. Replace the generic RuntimeError with the appropriate gRPC status codes based on these requirements:

  • If the account_id is not found in the database, return GRPC::NotFound.
  • If the amount is less than or equal to zero, return GRPC::InvalidArgument.
  • If the account has insufficient funds, return GRPC::FailedPrecondition.
# The current, broken implementation
class PaymentService < Payments::Service::Service
  def process_payment(call)
    account = Account.find_by(id: call.request.account_id)
    
    # TODO: Handle missing account
    raise "Account not found" if account.nil?

    # TODO: Handle invalid amount
    raise "Amount must be positive" if call.request.amount <= 0

    if account.balance < call.request.amount
      # TODO: Handle insufficient funds
      raise "Insufficient funds in account"
    end

    account.charge!(call.request.amount)
    Payments::PaymentResponse.new(success: true, transaction_id: "TXN123")
  end
end
Rating
0 0

There are no comments for now.

to be the first to leave a comment.