error-handlinggo

Go checking for the type of a custom Error


I am having a hard time using a custom Error type in Go. I read this Blog post on Errors

So I tried this:

In my model.go I defined a custom error:

type ModelMissingError struct {
    msg string // description of error
}

func (e *ModelMissingError) Error() string { return e.msg }

In one of my methods I throw a custom error like this:

...
return Model{}, &ModelMissingError{"no model found for id"}
...

In the caller of that method I would like to check the error returned for its type and take action if it is in fact a ModelMissingError.

How can I do this?

I tried this:

if err == model.ModelMissingError 

The result is *type model.ModelMissingError is not an expression*

Clearly I am missing something.


Solution

  • Reading the Blog post further exposes a bit of Go like this:

    serr, ok := err.(*model.ModelMissingError)
    

    This is the comma ok idiom, clearly I need to re do my go lang tour

    A type assertion provides access to an interface value's underlying concrete value. t := i.(T) This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t. If i does not hold a T, the statement will trigger a panic. To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.