Creating gRPC Errors in Go with Status Codes

Kieran Warwick
Thirdfort

--

This explains the use of the GRPCStatus within errors types to provide a code with your error message. The purpose of this method is to convert an error into a status, which is called internally when a server is producing an status from an error with the interface type

Let us assume that we use a custom Error type to hold both the error message and status code.

We also assume that the error method is implemented, such that our custom error implements the error interface. This is how I have set up mine:

Now we have a custom error type, we can add the GRPCStatus method to the error which I will define as such:

This method is the key to returning codes in gRPC, as the gRPC server used by google.golang.org/grpc will convert an interface error into a Status with a code.

To do this, it checks if the error implements GRPCStatus() *Status. If it does not, it will return a status with the error message, and a status of 2 (UNKNOWN).

Because we have implemented the GRPCStatus() *Status method, which creates a new status using the code defined within the error, it will return with the correct code.

For completeness, to create these errors from other packages, we create a constructor function, which takes in the status code and the error message. This will then return the error interface type to ensure that the gRPC server will convert that interface to a status type, which in turn will force it to use our GRPCStatus method.

The full code gist can be found below for my custom error type

At Thirdfort, we’re on a mission to make moving house easier for everyone involved. We use tech, design, and data to make working with clients secure and friction-free for lawyers, property, and finance professionals. Since launching in 2017, we’ve grown from a single London office to an international team with sites in Manchester and Sri Lanka. We’re backed by leading investors like Alex Chesterman (Founder of Zoopla and Cazoo) and HM Land Registry.

Want to help shape Thirdfort’s story in 2022? We’d love to hear from you. Find your next role on our Careers Hub or reach out to careers@thirdfort.com.

--

--