去检查自定义错误的类型

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.

Ahh, I think I got it. I am a dum dum. 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

I have manged to make an error assertion using the switch statement as follows:

 err := FuncModelMissingError()

 switch t := err.(type) {
 default:
     fmt.Println("not a model missing error")
 case *ModelMissingError:
     fmt.Println("ModelMissingError", t)
}

I hope this helps you out.