HiveBrain v1.2.0
Get Started
← Back to all entries
debuggoCritical

Go checking for the type of a custom Error

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
errortheforcheckingtypecustom

Problem

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.

Code Snippets

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

Context

Stack Overflow Q#23796543, score: 138

Revisions (0)

No revisions yet.