Force return error in golang

huangapple go评论75阅读模式
英文:

Force return error in golang

问题

我想测试某段代码如何处理错误。

我想要一个函数返回一个错误。

我尝试过输入 return 0/0,但是我的应用程序无法构建。

我如何强制返回一个错误?

英文:

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?

答案1

得分: 19

你可以像这样返回错误:

func ReturnError() (string, error){       
      return "", fmt.Errorf("这是一个%s错误", "内部服务器")
      // 或者
      return "", errors.New("这是一个错误")
}
英文:

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")
}

答案2

得分: 12

你可以使用errors包。

import "errors"

// [ ... ]

func failFunc() error {
    return errors.New("错误消息")
}

这是godoc链接:https://godoc.org/errors

英文:

You can use the errors package.

import "errors"

// [ ... ]

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

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

huangapple
  • 本文由 发表于 2016年3月30日 22:02:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/36311182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定