Go: return false or return a custom error ErrValueNotFound?

When retrieving a value from a map, if the value doesn't exist, it returns a false, not a custom error ErrValueNotFound.

According tohttps://go.dev/blog/error-handling-and-goarrow-up-rightThe definition of error in Go is: error is for exceptional situations. My initial thought was: how can data not being found be an exceptional situation?

But in that article, there is an example that calls a Get function which doesn't return a bool but returns an error, see: [highlight link](https://go.dev/blog/error-handling-and-go#:~:text=if%20err%20%3A%3D%20datastore.Get(c%2C%20key%2C%20record)%3B%20err%20!%3D%20nil%20%7B%0A%20%20%20%20%20%20%20%20return%20%26appError%7Berr%2C%20%22Record%20not%20found%22%2C%20404%7D%0A%20%20%20%20%7Darrow-up-right)

Even though the official example is written that way, I still feel uncomfortable returning a custom error.

When calling gorm, if you encounter an error like ErrRecordNotFound, you separate it from other errors and you often write

if errors.Is(err,gorm.ErrRecordNotFound){...}

When calling gorm, if it returns gorm.ErrRecordNotFound, I will return a bool and set err to nil.

After writing it many times I realized that in some scenarios, a record not being found can indeed be considered an exceptional situation — for example, when using sessions, not finding it in the cache is an exception. In that case, adding a bool is unnecessary.

Last updated