Skip to main content

# Exceptions in gRPC

## Throwing exceptions​

Any ASP.NET Core gRPC service can send an error response by throwing an `RpcException`, which can be caught by the client as if it were in the same process. The `RpcException` must include a status code and description, and can optionally include metadata and a longer exception message. The metadata can be used to send additional data.

Throwing an exception example

    ...
    var metadata = new Metadata { { "User", user.Identity.Name } };
    throw new RpcException(new Status(StatusCode.PermissionDenied, "Permission denied"), metadata);
    ...

## Catching exceptions​

Catching an exception

    try {
         var result = await client.MyMethod(new GetPortfolioRequest { Id = id });
       }
       catch (RpcException ex) when (ex.StatusCode == StatusCode.PermissionDenied)
        {
            var userEntry = ex.Trailers.FirstOrDefault(e => e.Key == "User");
            Console.WriteLine($"User '{userEntry.Value}' does not have permission to view this.");
        }
     catch (RpcException)
      {
        //other ex type
      }

title

When you provide additional metadata for errors, be sure to document the relevant keys and values in your API documentation, or in comments in your .proto file.