Motivation
I have custom error type named CustomError and I want to write a method that parses any type of error into my error structure. So I wrote parse method to show you. I will use the parse method on any function that returns error interface. So all errors will be structured with my type.
Problem
When I use parse method with nil value to return error interface, the returning error is not nil. Code is below. First test succeeded but second did not.
const ( UnHandledError = "UnHandledError" CircuitBreakerError = "CircuitBreakerError" ) type CustomErrorType struct { Key string Message string Status int } func (c *CustomErrorType) Error() string { return "Custom error message" } func parse(err error) *CustomErrorType { if err == nil { return nil } if e, ok := err.(*CustomErrorType); ok { return e } if e, ok := err.(hystrix.CircuitError); ok { return &CustomErrorType{CircuitBreakerError, e.Message, http.StatusTooManyRequests} } return &CustomErrorType{UnHandledError, err.Error(), http.StatusInternalServerError} } func TestParse_it_should_return_nil_when_error_is_nil(t *testing.T) { result := parse(nil) if result != nil { t.Error("result is not nil") } } func TestParse_it_should_return_nil_when_error_is_nil_2(t *testing.T) { aFunc := func() error { return parse(nil) } result := aFunc() if result != nil { t.Error("result is not nil") } } Can you explain what am I missing or what is wrong?