Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error concrete type

Tags:

go

I have a method CreateProduct(&Product) error that returns a value implementing error interface. It can be a gorm database error or my own error type.

Having the returned value, how can I know which type is the error?

err = api.ProductManager.CreateProduct(product)
if err != nil {
    // TODO: how to distinguish that it is a validation error?
    response.WriteHeader(422)
    response.WriteJson(err)
    return
}
like image 992
warvariuc Avatar asked Sep 14 '26 13:09

warvariuc


1 Answers

You can do a type assertion, and act if the error returned is from the expected type:

if nerr, ok := err.(yourError); ok  {
  // do something
}

You can also do a type switch for multiple test

switch t := err.(type) {
case yourError:
    // t is a yourError
case otherError :
    // err is an otherError
case nil:
    // err was nil
default:
    // t is some other type 
}

Note: a type assertion is possible even on nil (when err == nil):

the result of the assertion is a pair of values with types (T, bool).

  • If the assertion holds, the expression returns the pair (x.(T), true);
  • otherwise, the expression returns (Z, false) where Z is the zero value for type T

Here, the "zero value" of "Error" would be nil.

like image 90
VonC Avatar answered Sep 16 '26 06:09

VonC