user1283776
user1283776

Reputation: 21764

Force return error in golang

I want to test how certain code handles errors.

I want a function to return an error.

I have tried typing return 0/0 but then my application won't build

How can I force return an error?

Upvotes: 11

Views: 7089

Answers (2)

codefreak
codefreak

Reputation: 7131

you can return errors like this:

func ReturnError() (string, error){       
      return "", fmt.Errorf("this is an %s error", "internal server")
      // or
      return "", errors.New("this is an error")
}

Upvotes: 20

nessuno
nessuno

Reputation: 27042

You can use the errors package.

import "errors"

// [ ... ]

func failFunc() error {
    return errors.New("Error message")
}

Here's the godoc: https://godoc.org/errors

Upvotes: 12

Related Questions