Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert on error types in Go tests?

I have a error type like below defined

type RetryableError struct {
    msg string
}

func (a *RetryableError) Error() string {
    return a.msg
}

In a unit test, what is the Go way of asserting if the error returned is of RetryableError type?

like image 282
Anirudh Jayakumar Avatar asked Sep 05 '25 03:09

Anirudh Jayakumar


1 Answers

Use type assertion:

err := someFunc()
if retryable, ok := err.(*RetryableError); ok {
   // use retryable
}

Your RetryableError is not an error, but *RetryableError is. To correct:

func (a RetryableError) Error() string {
    return a.msg
}
like image 189
Burak Serdar Avatar answered Sep 07 '25 18:09

Burak Serdar