In Golang, we return errors explicitly using the return statement. This contrasts with the exceptions used in languages like java, python. The approach in Golang to makes it easy to see which function returns an error?
在Golang中,我們使用return語句顯式返回錯誤。 這與Java,Python等語言中使用的例外形成對比。 Golang中的方法可以輕松查看哪個函數返回錯誤 ?
In Golang, errors are the last return value and have type error, a built-in interface.
在Golang中,錯誤是最后一個返回值,其錯誤類型為內置接口。
errors.New() is used to construct basic error value with the given error messages.
errors.New()用于根據給定的錯誤消息構造基本錯誤值。
We can also define custom error messages using the Error() method in Golang.
我們還可以使用Golang中的Error()方法定義自定義錯誤消息 。
How to create an error message in Golang?
如何在Golang中創建錯誤消息?
Syntax:
句法:
err_1 := errors.New("Error message_1: ")
err_2 := errors.New("Error message_2: ")
Basic program to test an error in Golang
測試Golang錯誤的基本程序
package main
import (
"fmt"
"errors"
)
func test(value int) (int, error) {
if (value == 0) {
return 0, nil;
} else {
return -1, errors.New("Invalid value: ")
}
}
func main() {
value, error := test(10)
fmt.Printf("Value: %d, Error: %v", value, error)
value, error = test(0)
fmt.Printf("\n\nValue: %d, Error: %v", value, error)
}
Output
輸出量
Value: -1, Error: Invalid value:
Value: 0, Error: <nil>
翻譯自: https://www.includehelp.com/golang/how-to-return-an-error-in-golang.aspx