Error Handling

Error

The error type is an interface type. An error variable represents any value that can describe itself as a string.

type error interface {
    Error() string
}

Error handling in Go

Errors are values in Go. You can choose either to panic or return the error as a value.

func (s *Eater) eat(food *Food) error {
    if food == nil {
        return errors.New("not given food")
    }

    food.Status = "eaten"
    return nil // zero value of error is nil
}

func (s *Eater) eatOrPanic(food *Food) {
    if food == nil {
        panic("not given food")
    }
    
    food.Status = "eaten"
}

If you want to recover from a panic and return a value, take a look at this: Effective Go - Recover.

Custom Error Wrapper

Here's an example(excuse me for coming up with a bad one).

type AppError struct {
    Err error
    Message string
    Code int
}

func (e *AppError) Error() string {
    return e.Message
}

func NewAppError(err error, message string, code int) *AppError {
    return &AppError{Err: err, Message: message, Code: code}
}

func NewBadRequestError(err message string) *AppError {
    return NewAppError(err, message, 400)
}

// ...
func (s *UserService) FindAll() ([]*User, *AppError) {
    users, err := s.repo.FindAll()
    if err != nil {
        return nil, NewInternalServerError(err, "could not fetch users")
    }
    return users, nil
}

References

Last updated