Errors

Error handling and errors produced by Go Micro

Go Micro provides abstractions and types for most things that occur in a distributed system including errors. By providing a core set of errors and the ability to define detailed error types we can consistently understand what’s going on beyond the typical Go error string.

Overview

We define the following error type:

  1. type Error struct {
  2. Id string `json:"id"`
  3. Code int32 `json:"code"`
  4. Detail string `json:"detail"`
  5. Status string `json:"status"`
  6. }

Anywhere in the system where you’re asked to return an error from a handler or receive one from a client you should assume its either a go-micro error or that you should produce one. By default we return errors.InternalServerError where somethin has gone wrong internally and errors.Timeout where a timeout occurred.

Usage

Let’s assume some error has occurred in your handler. You should then decide what kind of error to return and do the following.

Assuming some data provided was invalid

  1. return errors.BadRequest("com.example.srv.service", "invalid field")

In the event an internal error occurs

  1. if err != nil {
  2. return errors.InternalServerError("com.example.srv.service", "failed to read db: %v", err.Error())
  3. }

Now lets say you receive some error from the client

  1. pbClient := pb.NewGreeterService("go.micro.srv.greeter", service.Client())
  2. rsp, err := pb.Client(context, req)
  3. if err != nil {
  4. // parse out the error
  5. e := errors.Parse(err.Error())
  6. // inspect the value
  7. if e.Code == 401 {
  8. // unauthorised...
  9. }
  10. }