Six Error handling tips in Go

Natan
4 min readMar 5, 2021

Error handling is very important in software development.

1. A missing value is an error

Assume we have UserRepo and want to define a method to get User by id .

1) C++/Java style

func (s *UserRepo) Get(ctx context.Context, id int64) (*User)

2) Go Style

func (s *UserRepo) Get(ctx context.Context, id int64) (u *User, err error)

Someone prefers to use err as DB query error, u = nil to represent user not found, which would bring troubles to the caller.

u, err := userRepo.Get(ctx, id)
if err != nil {
return err
}
if u != nil {
return errors.New("user not found")
}
...

Actually, we should use err to represent user not found , e.g. declare an error ErrNotExist . If err is not nil, u is nil or invalid value. Thus, the caller only needs to check one value instead of two.

u, err := userRepo.Get(ctx, id)
if err != nil {
return err
}
...

2. Never ignore any error

Rember to check every error. Usually, we have two options:
1) Handle error appropriately
2) Return error if you don’t know how to handle
Avoid using panic , most errors can be handled or recoverable.

--

--

Natan

Senior Software Engineer. Used to work with Tencent, Alibaba and Amazon.