Friday, April 12, 2024
HomeGolangThe right way to do higher Error Dealing with with Golang

The right way to do higher Error Dealing with with Golang


  • Errors as uint64 for higher efficiency
  • By conference, 0 is “OK” or “no error”
  • Use the exhaustive linter with change
  • Use enums to outline error circumstances
  • Implement Stringer on enums for human readable error messages
  • Use generic T ~uint64 to kind customized structs to errors

I’ve been making an attempt to determine a greater Golang error dealing with sample. In my earlier posts, I alluded to a possible answer, however after some experimentation, it was inadequate. After revisiting and coming again to this subject a number of extra occasions, I believe I hit on one thing. The very best half is that this requires no exterior dependencies and doesn’t require wholesale conversions to this new sample.

Defining an Error in Golang

Defining what an error is will get us to the foundation of the problem. Often, in Golang, an error is often a string or a struct containing a string worth. However when one thing fails in a perform, generally there isn’t any purpose to return a complete human-readable string. Returning an integer fixed that identifies the error will be simply nearly as good.


Why an integer, although? If we look at error, we are able to see that it’s an interface and due to this fact utilizing it can trigger the worth to flee to the heap. Which means all errors are heap allocations. Whereas golang makes use of rubbish assortment, too many heap allocations could cause efficiency points throughout your utility. Think about a scenario the place an utility runs nominally and instantly an inflow of errors happens. You wouldn’t desire a spike in error worth allocations to trigger an surprising CPU spike that would probably ripple by a system. Defining errors  uint64 solves that drawback. That can be heap allocation free.

  • Takeaway: Errors as uint64 for higher efficiency

Case examine: Golang’s context.Context

Allow us to take Err() error from context.Context for instance. Within the perform feedback, it primarily states that it returns certainly one of:

  • No error (nil)
  • var Canceled = errors.New(“context canceled”)
  • var DeadlineExceeded error = deadlineExceededError{}

We are able to already take that description and use it immediately in our first new error sample instance.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments