Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
201: Error Handling in gRPC Services
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_idis not found in the database, returnGRPC::NotFound. - If the
amountis less than or equal to zero, returnGRPC::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
There are no comments for now.