How to unit test Go errors

In most cases you can just check if the error is not nil.

I’d recommend not checking error strings unless absolutely necessary. I generally consider error strings to be only for human consumption.

If you need more detail about the error, one better alternative is to have custom error types. Then you can do a switch over the err.(type) and see if it’s a type you expect.
If you need even more detail, you can make the custom error types contain values which you can then check in a test.

Go’s error is just an interface for a type that has an Error() string method, so implementing them yourself is straightforward.
https://blog.golang.org/error-handling-and-go

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)