Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force return error in golang

Tags:

go

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?

like image 695
user1283776 Avatar asked Mar 30 '16 14:03

user1283776


People also ask

How do you return an error in Golang?

Errors can be returned as nil , and in fact, it's the default, or “zero”, value of on error in Go. This is important since checking if err != nil is the idiomatic way to determine if an error was encountered (replacing the try / catch statements you may be familiar with in other programming languages).

How do I print err in Go?

You can create wrapped errors by using the %w flag with the fmt. Errorf function as shown in the following example. As you can see the application prints both the new error created using fmt. Errorf as well as the old error message that was passed to the %w flag.

How do you wrap an error in Go?

Syntax for wrapping an error in Golang First we need to create a new error using errors. New() followed by fmt. Errorf() with the %w verb to wrap the error.


2 Answers

You can use the errors package.

import "errors"

// [ ... ]

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

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

like image 116
nessuno Avatar answered Oct 13 '22 05:10

nessuno


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")
}
like image 44
codefreak Avatar answered Oct 13 '22 06:10

codefreak