debuggoCritical
Go checking for the type of a custom Error
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:
In one of my methods I throw a custom error like this:
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
How can I do this?
I tried this:
The result is
Clearly I am missing something.
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.ModelMissingErrorThe result is
type model.ModelMissingError is not an expressionClearly I am missing something.
Solution
Reading the Blog post further exposes a bit of Go like this:
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.
If
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.
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.