frequenz-floss / frequenz-api-dispatch

gRPC+protobuf specification and Python bindings for the Frequenz Dispatch API
https://frequenz-floss.github.io/frequenz-api-dispatch/
MIT License
1 stars 6 forks source link

Document error response behavior #144

Open stefan-brus-frequenz opened 7 months ago

stefan-brus-frequenz commented 7 months ago

What's needed?

The error conditions that can arise for each type of request should be documented, as should the expected behavior of the server, including the expected response code.

Marenz commented 7 months ago

Some information provided by gemini:

Here's how gRPC error handling works in Python, and how to check for errors when making gRPC calls:

gRPC Error Model

gRPC uses a status code system to signal errors, similar to HTTP status codes but tailored for RPCs. These status codes provide a standardized way to understand error cases:

Handling Errors in Python

gRPC errors in Python are raised as grpc.RpcError exceptions. Here's how to handle them:

import grpc

try:
    response = await self._stub.GetMicrogridDispatch(request)
    # Process the successful response here

except grpc.RpcError as error:
    status_code = error.code()  # Get the gRPC status code
    details = error.details()   # Optional error details as a string 

    # Example of handling based on status code
    if status_code == grpc.StatusCode.NOT_FOUND:
        print("Resource not found!")
    elif status_code == grpc.StatusCode.PERMISSION_DENIED:
        print("Insufficient permissions")
    else: 
        print(f"Error occurred: {status_code} - {details}")

Explanation:

  1. Wrap the call in a try-except block: This allows you to capture the grpc.RpcError.
  2. Retrieving Information:
    • error.code(): Provide the gRPC status code as a grpc.StatusCode enum.
    • error.details(): Provides an optional string with more specific error information.
  3. Conditional Handling: Handle specific error types based on the status code.
  4. Generic Error Handling: For broader or unknown errors, log the status code and details.

Important Notes:

Let me know if you have a specific error scenario or status code you would like help with handling!

llucax commented 7 months ago

If we don't want to expose gRPC/protobuf in the clients, we should probably wrap these gRPC errors in the clients too. So we should probably add these wrappers in https://github.com/frequenz-floss/frequenz-client-base-python.