如何在Golang中返回错误?

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

How to return the errors in golang?

问题

在这段代码中,我从环境变量中获取数据,并使用它发送电子邮件到给定的地址。只有在排除代码中的错误时才能正常工作。我返回了错误并在中间件中使用它们,因为我不想每次都使用log.Fatal(err)。但是它给我两个错误。

1. 无法将未命名字符串常量“”用作[4]string值在返回语句中

2. 代码无法执行无法访问的返回语句

func LoadEnvVariable(key string) (string, error) {
    viper.SetConfigFile(".env")
    err := viper.ReadInConfig()
    return "", err

    value, ok := viper.Get(key).(string)
    if !ok {
        return "", err
    }
    return value, nil
}

func Email(value [4]string) ([4]string, error) {
    mail := gomail.NewMessage()

    myEmail, err := LoadEnvVariable("EMAIL")
    return "", err
    appPassword, err := LoadEnvVariable("APP_PASSWORD")
    return "", err

    mail.SetHeader("From", myEmail)
    mail.SetHeader("To", myEmail)
    mail.SetHeader("Reply-To", value[1])
    mail.SetHeader("subject", value[2])
    mail.SetBody("text/plain", value[3])

    a := gomail.NewDialer("smtp.gmail.com", 587, myEmail, appPassword)
    err = a.DialAndSend(mail)
    return "", err

    return value, nil
}
英文:

In this code, I am taking the data from the environment variable and using it to send the email to the given address. It only works if I exclude the errors from the code. I returned the errors and used them in middleware because I don't want to use log.Fatal(err) every time. But it gives me two errors.

1. cannot use "" (untyped string constant) as [4]string value in return statement

2. code can not execute unreachable return statement

func LoadEnvVariable(key string) (string, error) {
	viper.SetConfigFile(".env")
	err := viper.ReadInConfig()
	return "", err

	value, ok := viper.Get(key).(string)
	if !ok {
		return "", err
	}
	return value, nil
}

func Email(value [4]string) ([4]string, error) {
	mail := gomail.NewMessage()

	myEmail, err := LoadEnvVariable("EMAIL")
	return "", err
	appPassword, err := LoadEnvVariable("APP_PASSWORD")
	return "", err

	mail.SetHeader("From", myEmail)
	mail.SetHeader("To", myEmail)
	mail.SetHeader("Reply-To", value[1])
	mail.SetHeader("subject", value[2])
	mail.SetBody("text/plain", value[3])

	a := gomail.NewDialer("smtp.gmail.com", 587, myEmail, appPassword)
	err = a.DialAndSend(mail)
	return "", err

	return value, nil
}

答案1

得分: 0

> 使用此代码检查错误

if err != nil {
    return "", err
}

func LoadEnvVariable(key string) (string, error) {
    viper.SetConfigFile(".env")
    err := viper.ReadInConfig()
    if err != nil {
        return "", err
    }

    value, ok := viper.Get(key).(string)
    if !ok {
        return "", err
    }
    return value, nil
}

func Email(value [4]string) ([4]string, error) {
    mail := gomail.NewMessage()

    myEmail, err := LoadEnvVariable("EMAIL")
    if err != nil {
        return "", err
    }

    appPassword, err := LoadEnvVariable("APP_PASSWORD")
    if err != nil {
        return "", err
    }

    mail.SetHeader("From", myEmail)
    mail.SetHeader("To", myEmail)
    mail.SetHeader("Reply-To", value[1])
    mail.SetHeader("subject", value[2])
    mail.SetBody("text/plain", value[3])

    a := gomail.NewDialer("smtp.gmail.com", 587, myEmail, appPassword)
    err = a.DialAndSend(mail)
    if err != nil {
        return "", err
    }

    return value, nil
}
英文:

> use this to check error

   if err != nil { 	
       return "", err 
    }

func LoadEnvVariable(key string) (string, error) {
        viper.SetConfigFile(".env")
        err := viper.ReadInConfig()
        if err != nil {
    		return "", err
    	}
    
        value, ok := viper.Get(key).(string)
        if !ok {
            return "", err
        }
        return value, nil
    }
    
    func Email(value [4]string) ([4]string, error) {
        mail := gomail.NewMessage()
    
        myEmail, err := LoadEnvVariable("EMAIL")
        if err != nil {
    		return "", err
    	}
    
        appPassword, err := LoadEnvVariable("APP_PASSWORD")
        if err != nil {
    		return "", err
    	}
    
        mail.SetHeader("From", myEmail)
        mail.SetHeader("To", myEmail)
        mail.SetHeader("Reply-To", value[1])
        mail.SetHeader("subject", value[2])
        mail.SetBody("text/plain", value[3])
    
        a := gomail.NewDialer("smtp.gmail.com", 587, myEmail, appPassword)
        err = a.DialAndSend(mail)
        if err != nil {
    		return "", err
    	}
    
        return value, nil
    }

答案2

得分: 0

首先,在返回之前,要先检查err是否为nil,以进行错误处理!

所以不要这样写:

myEmail, err := LoadEnvVariable("EMAIL")
return "", err

而是应该这样写:

myEmail, err := LoadEnvVariable("EMAIL")
if err != nil {
    return "", err
}

其次,单个字符串类型""可以兼容固定大小为[4]string的数组。使用命名返回变量可能会更方便,这样在出现错误时就不需要传递显式的“零”值了。所以可以这样定义函数签名:

func Email(in [4]string) (out [4]string, err error) {

    myEmail, err := LoadEnvVariable("EMAIL")
    if err != nil {
        return // 隐式返回 'out' 和 'err'
    }

    // ...

    out = in
    return  // 隐式返回 'out' 和 nil 'err'
}
英文:

Firstly, to error handle, check if err is nil before returning!

So not:

myEmail, err := LoadEnvVariable("EMAIL")
return "", err

but instead:

myEmail, err := LoadEnvVariable("EMAIL")
if err != nil {
    return "", err
}

Secondly, a single string type "" is compatible to a fixed array size of [4]string. It may make your life easier to use named return variables, so you don't need to pass a explicit "zero" value in the event of an error. So define your function signature like so:

func Email(in [4]string) (out [4]string, err error) {

    myEmail, err := LoadEnvVariable("EMAIL")
    if err != nil {
        return // implicitly returns 'out' and 'err'
    }

    // ...

    out = in
    return  // implicitly returns 'out' and nil 'err'
}

huangapple
  • 本文由 发表于 2021年10月26日 21:37:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/69724164.html
匿名

发表评论

匿名网友

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

确定