Go Series Tutorial--30. Error handling

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Welcome to the 30th chapter of [Golang Series Tutorial] (HTTPS://STUDYGOLANG.COM/SUBJECT/2). # # What's wrong? An error indicates an exception occurred in the program. For example, when we try to open a file, the file system does not have the file. This is the exception, which is represented by an error. In Go, errors are always common. Errors are represented by the built-in ' error ' type. Like other built-in types (such as ' int ', ' float64 ', etc.), error values can be stored in variables, as function return values, and so on. # # example Now we begin to write an example that attempts to open a file that does not exist. "' Gopackage mainimport (" FMT "" OS ") Func main () {f, err: = OS. Open ("/test.txt") if err! = Nil {fmt. PRINTLN (ERR) return} FMT. Println (F.name (), "opened successfully")} "[Run in Playground] (https://play.golang.org/p/yOhAviFM05) on line 9th of the program, We tried to open the file with the path '/test.txt ' (playground obviously does not exist for this file). The [' Open '] (https://golang.org/pkg/os/#Open) function in the ' OS ' package has the following signature: ' ' Gofunc Open (name string) (file *file, err Error) ' * * If the file is opened successfully, the ' open ' function returns a file handle (filename Handler) and an error with a value of ' nil '. If an error occurs when opening a file, an error that is not equal to ' nil ' is returned. If a [function] (https://studygolang.com/articles/11892) or [method] (https://studygolang.com/articles/12264) returns an error, by convention, The error is returned as the last value. The ' Open ' function also takes ' err ' as the last return value. * * According to GO conventions, when dealing with errors, the return error is usually compared to ' nil '. The ' nil ' value indicates that no error occurred, not a ' nil ' value indicating the presenceThe error * *. Here, our 10th line checks if the error value is ' nil '. If it is not ' nil ', we will simply print out the error and return it in the ' main ' function. Running the program outputs: "' Open/test.txt:no such file or directory ' is great! We got an error that states that the file does not exist. # # Error type representation let's go deeper and understand how the ' error ' type is defined. ' Error ' is an [interface] (https://studygolang.com/articles/12266) type, defined as follows: ' Gotype Error interface {error () string} ' error ' There is a method that has a signature of ' Error () string '. All types that implement the interface can be treated as an error type. The ' Error () ' method gives a description of the error. ' FMT. Println ' ERROR () string ' method is called internally to get a description of the error when printing errors. The 11th line in the previous section of the example prints out the wrong description. # # different ways to get more information from the error now that we know that ' error ' is an interface type, let's see how to get more information from an error. In the previous example, we just printed out the wrong description. If we want to know the wrong file path, what should we do? One option is to parse the wrong string directly. This is the output of the preceding example: "' Open/test.txt:no such file or directory" * * We parse this error message, although we get the path of the file where the error occurred, this method is not elegant. As the language version is updated, the description of this error can change at any time, making our program error * *. Is there a more reliable way to get the file name? The answer is yes, it can be done, the Go standard library gives a variety of methods to extract error-related information. Let's take a look at it. # # 1. Assert the underlying struct type and use the struct field for more information if you read the document of the [' Open '] (https://golang.org/pkg/os/#OpenFile) function carefully, you can see that the error type it returns is ' *patherror '. [' Patherror '] (https://golang.org/pkg/os/#PathError) is [structure] (HTTPS://STUDYGOLANG.COM/ARTICLES/12263) type, which is implemented in the standard library as follows: "' Gotype patherror struct {Op string Path string Err error}func (e *patherror) error () string {Retu RN E.op + "+ E.path +": "+ E.err.error ()}" If you are interested in knowing where the above source code appears, you can find it here: https://golang.org/src/os/error.go?s=653:716 #L11. With the code above, you know that ' *patherror ' implements the ' Error ' interface by declaring the ' error () string ' method. ' Error () string ' concatenation the file operation, path, and actual error and returns the string. So we get the error message: "' Open/test.txt:no such file or directory '" struct ' patherror ' ' path ' field, there is a path to the files that caused the error. We modify the previously written program to print out the path. "' Gopackage mainimport (" FMT "" OS ") Func main () {f, err: = OS. Open ("/test.txt") If err, OK: = Err. (*os. PATHERROR); OK {fmt. Println ("File at Path", err. Path, "failed to open") return} FMT. Println (F.name (), "opened successfully")} "[Run on Playground] (HTTPS://PLAY.GOLANG.ORG/P/JQRQWU7JF9) in the above program, we are in the 10th The row uses [type assertion] (https://studygolang.com/articles/12266), type assertion, to get the underlying value of the ' Error ' interface (underlying value). Next on line 11th, we use ' err. Path ' to print it. The program will output: ' File at Path/test.txt failed to open ' is great! We have successfully obtained the file path to the error using the type assertion. ### 2. Assert the underlying struct type, invoke the method to get more information the second way to get more error information is to assert the underlying type, and then get more information by calling the struct type's method. We understand this through an example. The ' dnserror ' struct type in the standard library is defined as follows: ' ' Gotype dnserror struct {...} Func (e *dnserror) Error () string {...} Func (e *dnserror) Timeout () bool {...} Func (e *dnserror) temporary () bool {...} "From the above code you can see that the ' dnserror ' struct also has ' timeout () bool ' and ' temporary () bool ' two methods, which return a Boolean value that indicates whether the error was caused by a time-out or a temporary error. Next we write a program that asserts the ' *dnserror ' type and calls these methods to determine whether the error is a temporary error or is caused by a timeout. "' Gopackage mainimport (" FMT "" NET ") Func main () {addr, err: = Net. Lookuphost ("golangbot123.com") If err, OK: = Err. (*net. DNSERROR); OK {if Err. Timeout () {fmt. PRINTLN ("Operation timed Out")} else if Err. Temporary () {FMT. PRINTLN ("Temporary Error")} else {fmt. PRINTLN ("Generic error:", err)} return} FMT. Println (Addr)} "* * Note: DNS resolution cannot be performed in playground. Please run the program in your local * *. In the above procedure, we tried to get the IP of ' golangbot123.com ' (invalid domain name) on line 9th. In line 10th, we pass ' *net. Dnserror ' type assertion, gets the underlying value of the error. In the next lines 11th and 13th, we checked separately whether the error was caused by a timeout or a temporary error. In this case, our error is neither a temporary error nor a timeout, so the program outputs: "' GenerIC error:lookup golangbot123.com:no Such host "If the error is a temporary error or is caused by a timeout, then the corresponding if statement executes, so we can handle them appropriately. # # 3. The third way to get more information about the error directly is to compare it directly to the ' error ' type of variable. We understand it through an example. The [' Glob '] (https://golang.org/pkg/path/filepath/#Glob) in the ' filepath ' package is used to return all filenames that satisfy the Glob pattern. If the pattern is not written, the function returns an error ' Errbadpattern '. The ' Errbadpattern ' in the ' filepath ' package is defined as follows: ' ' Govar errbadpattern = errors. New ("Syntax error in pattern") ' errors '. New () ' is used to create an error. We'll discuss it in more detail in the next tutorial. When the pattern is incorrect, the ' Glob ' function returns ' Errbadpattern '. Let's write a small program to see this error. "' Gopackage mainimport (" FMT "" Path/filepath ") func main () {files, error: = FilePath. Glob ("[") if error! = Nil && Error = = FilePath. Errbadpattern {fmt. PRINTLN (Error) return} FMT. Println ("Matched files", files)} ' [Run on Playground] (Https://play.golang.org/p/zbVDDHnMZU) in the above program, we queried the schema for the ' [' File, However, this pattern is not written correctly. We checked to see if the error was ' nil '. In order to get more information on this error, we will ' error ' directly with ' filepath ' on the 10th line. Errbadpattern ' compared. If the condition is met, then the error is caused by a pattern error. The program outputs: the "syntax error in pattern" Standard library uses the three methods mentioned above when providing detailed information about the error. In the next tutorial, we'll use these methods to create our own customError. # # Can't ignore the error never ignore the error. Ignoring mistakes can lead to problems. Next I rewrite the example above, and I omit the error-handling code when listing all the file names that satisfy the pattern. "' Gopackage mainimport (" FMT "" Path/filepath ") func main () {files, _: = FilePath. Glob ("[") fmt. Println ("Matched files", files)} ' [Run on Playground] (HTTPS://PLAY.GOLANG.ORG/P/2K8R_QG_LC) We have learned from the previous example that this pattern is wrong. In line 9th, by using the ' _ ' blank identifier, I ignored the error returned by the ' Glob ' function. I simply printed all the matching files on line 10th. The program outputs: ' ' matched files [] ' because I ignored the error, the output looks like there is no file matching the glob pattern, but this is actually because the pattern is not written. So never ignore the error. This concludes the tutorial. This tutorial discusses how to handle errors in the program and also discusses how to query for more information about the error. Briefly summarize what is discussed in this tutorial:-What is an error? -Error representations-Various methods of getting error details-can not ignore errors in the next tutorial, we will create our own custom errors and add more context to standard errors. Have a nice day. * * Previous tutorial-[Defer] (https://studygolang.com/articles/12719) * * * Next tutorial-[Custom Error] (https://studygolang.com/articles/12784) **

via:https://golangbot.com/error-handling/

Author: Nick Coghlan Translator: Noluye proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

2,189 Reads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.