Go Series Tutorial--31. Custom error

Source: Internet
Author: User
Tags sprintf
This is a creation in Article, where the information may have evolved or changed. [Custom Errors] (https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-series/custom-errors-golang-1.png) Welcome to the 31st chapter of [Golang Series Tutorial] (HTTPS://STUDYGOLANG.COM/SUBJECT/2). In [Previous tutorial] (https://studygolang.com/articles/12724), we learned how errors in Go are expressed and learned how to handle errors in standard libraries. We also learned to extract more information from the errors in the standard library. In this tutorial, we'll learn how to create our own custom errors and use it in the functions and packages we create. We will use the same techniques as in the standard library to provide more details about custom errors. # # Creating a custom error using the New function The simplest way to create a custom error is to use [' New ' in the [' Errors '] (https://golang.org/pkg/errors/) package (https://golang.org/pkg/ errors/#New) function. Before creating a custom error using new [function] (https://studygolang.com/articles/11892), let's take a look at how ' new ' is implemented. As shown below, is the implementation of the ' New ' function in [' Errors ' package] (https://golang.org/src/errors/errors.go?s=293:320#L1). "' go//package errors implements functions to manipulate Errors.package errors//New returns a error that formats as the Given Text.func New (text string) error {return &errorstring{text}}//errorstring is a trivial implementation of error . Type errorstring struct {s string}func (e *errorstring) Error () The implementation of the string {return e.s} ' New ' function is simple. ' ErrorString ' is a [struct] (https://studygolang.com/articles/12263) type, with only one string field ' s '. The 14th line uses the ' errorstring ' pointer receiver (Pointer Receiver) to implement the ' Error ' () string ' [method] ' of the ' Error ' interface (https://studygolang.com/articles/ 12264). The ' New ' function on line 5th has a string parameter that creates a variable of type ' errorstring ' and returns its address. It then creates and returns a new error. Now that we know how the ' new ' function works, we start using ' new ' in the program to create a custom error. We will create a simple program that calculates the radius of the circle and returns an error if the radius is negative. "' Gopackage mainimport (" Errors "" FMT "" math ") Func Circlearea (Radius float64) (float64, error) {if radius < 0 {return 0, errors. New ("area calculation failed, radius was less than zero")}return math. Pi * radius * radius, Nil}func Main () {radius: = -20.0area, err: = Circlearea (RADIUS) if err! = Nil {fmt. PRINTLN (Err) return}fmt. Printf ("Area of Circle%0.2f", area)} ' [Run on Glayground] (HTTPS://PLAY.GOLANG.ORG/P/_VUF6FGKQM) in the program above, We check if the radius is less than 0 (line 10th). If the radius is less than 0, we return an area equal to 0, along with the corresponding error message. If the radius is greater than 0, the area is computed and an error with the value ' nil ' is returned (line 13th). In the ' main ' function, we check if the error equals ' nil ' in line 19th. If it's not ' nil ', we'll print out the error and return it, otherwise we'll hitPrint out the area of the circle. In our program, the radius is smaller than 0, so print out: "Area calculation failed, radius is less than zero" # # Use Errorf to add more information to the error the above program works well, but if we can print out the current The radius of the circle, that's better. This will use the [' Errorf '] (https://golang.org/pkg/fmt/#Errorf) function in the [' FMT '] (https://golang.org/pkg/fmt/) package. The ' Errorf ' function specifies the wrong format based on the format specifier and returns a [string] (https://studygolang.com/articles/12261) that matches the error. Next we use the ' Errorf ' function to improve our program. "' Gopackage mainimport (" FMT "" math ") Func Circlearea (Radius float64) (float64, error) {if radius < 0 {return 0, FMT.E Rrorf ("area calculation failed, radius%0.2f are less than zero", radius)}return math. Pi * radius * radius, Nil}func Main () {radius: = -20.0area, err: = Circlearea (RADIUS) if err! = Nil {fmt. PRINTLN (Err) return}fmt. Printf ("Area of Circle%0.2f", area)} ' [Run on Playground] (HTTPS://PLAY.GOLANG.ORG/P/HQ7BVJT4O2) in the above program, we use ' Errorf ' (line 10th) prints the radius where the error occurred. After the program runs, it outputs: "Area calculation failed, radius-20.00 are less than zero" # # more information about using struct types and fields to provide errors can also be implemented with ' error ' [interface] (HTTPS : The structure of the//studygolang.com/articles/12266) is represented. This approach gives you more flexibility in handling errors。 In the example above, if we want to access the radius that caused the error, now the only way is to parse the wrong description of the message ' area calculation failed, radius-20.00 is less than zero '. This is not very good, because once the information is changed, the program will go wrong. We'll use the method in the standard library, in the previous tutorial, "asserting the underlying struct type, using struct fields for more information," which we explained in this way, using the struct field to access the radius that caused the error. We will create a struct type that implements the ' Error ' interface and use its fields to provide more information about the error. The first step is to create a struct type that represents the error. The naming convention for the type of error is that the name ends with ' error '. So we might as well name the struct type ' areaerror '. The struct type above "Gotype areaerror struct {err Stringradius float64}" has a ' radius ' field that stores the radius associated with the error, and the ' Err ' field stores the actual error information. The next step is to implement the ' Error ' interface. "' Gofunc (e *areaerror) Error () string {return FMT. Sprintf ("Radius%0.2f:%s", E.radius, E.err)} "" In the above code, we use the pointer receiver ' *areaerror ' to implement the ' Error ' () string ' method of the ' Error ' interface. The method prints a radius and a description of the error. Now let's write the ' main ' function and the ' circlearea ' function to complete the program. "' Gopackage mainimport (" FMT "" math ") type areaerror struct {err Stringradius float64}func (e *areaerror) Error () string {return FMT. Sprintf ("Radius%0.2f:%s", E.radius, E.err)}func Circlearea (radius float64) (float64, error) {if radius < 0 {return 0 , &areaerror{"radius is negative", Radius}}returnMath. Pi * radius * radius, Nil}func Main () {radius: = -20.0area, err: = Circlearea (RADIUS) if err! = Nil {If err, OK: = Err. ( *AREAERROR); OK {fmt. Printf ("Radius%0.2f is less than zero", Err.radius) return}fmt. PRINTLN (Err) return}fmt. Printf ("area of Rectangle1%0.2f", area)} ' [Run on Playground] (HTTPS://PLAY.GOLANG.ORG/P/OTS7J0ADQG) in the program above, ' Circlearea ' (line 17th) is used to calculate the area of the circle. The function first checks if the radius is less than 0, and if it is less than 0, it creates a value of type ' Areaerror ' by the error radius and corresponding error message, and then returns the address of the ' areaerror ' value, while ' area ' equals 0 (line 19th). * * So we provide more error information (that is, the radius that caused the error), we use the struct field of the custom error to define it * *. If the radius is non-negative, the function calculates and returns the area on line 21st, with the error value ' nil '. In the 26 line of the ' main ' function, we tried to calculate the area of the circle with a radius of-20. Because the radius is less than 0, it causes an error. We checked in line 27th if the error was ' nil ' and asserted the ' *areaerror ' type on the next line. * * If the error is ' *areaerror ' type, we can use ' Err.radius ' to get the wrong radius (line 29th), print the message from the definition error, and finally return the program to exit * *. If an assertion error is asserted, we print the error on line 32nd and return. If no error occurs, the area is printed in the 35th row. The program outputs: ' Radius-20.00 is less than zero ' below we'll use the [second method] mentioned in the previous tutorial (https://studygolang.com/articles/12724), Use the method of the custom error type to provide more information about the error. # # Use the struct type method to provide more information about the error in this section, we will write a program that calculates the rectangular area. If the length or width is less than 0, the program prints an error. TheOne step is to create a struct that represents the error. "' Gotype areaerror struct {err string//error descriptionlength float64//length which caused the errorwidth float64//w Idth which caused the structure type above has an error description field and can raise the width and height of the error. Now that we have the error type, let's implement the ' Error ' interface and add two methods to the error type to give it more error information. "' Gofunc (e *areaerror) Error () string {return E.err}func (e *areaerror) lengthnegative () bool {return E.length < 0} Func (e *areaerror) widthnegative () bool {return E.width < 0} "" In the code snippet above, we return a description of the error from the ' error () string ' method. When ' length ' is less than zero, ' lengthnegative () bool ' method returns ' true ', while ' width ' is less than zero, ' widthnegative () bool ' method returns ' true '. * * Both methods provide more information about the error, where it prompts us to calculate the cause of the area failure (a negative length or a negative width). So we have two error-type struct methods to provide more error information * *. The next step is to write a function that calculates the area. "' Gofunc rectarea (length, Width float64) (float64, error) {err: =" "If length < 0 {err + =" Length is less than zero} If width < 0 {if Err = = "" {err = "width is less than zero"} else {err + = ", width is less than zero"}}if err! = "" "{RE Turn 0, &areaerror{err, length, width}}return length * width, nil} ' the ' Rectarea ' function checks if the length or width is less than 0, and if less than 0, ' Rectarea ' returns an error message, otherwise ' rectarea ' returns the area of the rectangle and an error with a value of ' nil '. Let's create the ' main ' function to complete the program. "' Gofunc main () {length, Width: = -5.0, -9.0area, err: = Rectarea (length, width) if err! = Nil {If err, OK: = Err. ( *AREAERROR); OK {if err.lengthnegative () {fmt. Printf ("Error:length%0.2f is less than zero\n", err.length)}if err.widthnegative () {fmt. Printf ("Error:width%0.2f is less than zero\n", Err.width)}return}fmt. PRINTLN (Err) return}fmt. Println ("Area of the Rect", area)} "in the ' main ' program, we checked whether the error was ' nil ' (line 4th). If the error value is not ' nil ', we will assert the ' *areaerror ' type on the next line. We then use the ' lengthnegative () ' and ' widthnegative () ' methods to check for errors because the length is less than 0 or the width is less than 0. This allows us to use the wrong struct type method to provide more error information. If no error occurs, the area of the rectangle is printed. Here is the code for the entire program for your reference. ' Gopackage mainimport ' fmt ' type areaerror struct {err string//error descriptionlength float64//length which caused th E errorwidth float64//width which caused the Error}func (e *areaerror) error () string {return E.err}func (e *areaerror) Lengthnegative () bool {return E.Length < 0}func (e *areaerror) widthnegative () bool {return E.width < 0}func rectarea (length, width float64) (float (Error) {err: = "" If length < 0 {err + = "Length is less than zero"}if width < 0 {if Err = = "" {err = "width is l ESS than zero "} else {err + =", width is less than zero "}}if err! =" "{return 0, &areaerror{err, length, Width}}retur N Length * width, nil}func main () {length, Width: = -5.0, -9.0area, err: = Rectarea (length, width) if err! = Nil {if err, OK: = Err. (*areaerror); OK {if err.lengthnegative () {fmt. Printf ("Error:length%0.2f is less than zero\n", err.length)}if err.widthnegative () {fmt. Printf ("Error:width%0.2f is less than zero\n", Err.width)}return}fmt. PRINTLN (Err) return}fmt. Println ("Area of rect", area)} ' [Run on Playground] (https://play.golang.org/p/iJv2V8pZ7c) The program prints output: ' ' Error:length- 5.00 is less than zero error:width-9.00 was less than zero "in the previous tutorial [error handling] (https://studygolang.com/articles/12724), we introduced three To provide more error information, now we've looked at two of them. The third method ofThe use of direct comparison, relatively simple. I leave it to the reader as an exercise, and you can try to use this method to give more information about the custom error. This concludes the tutorial. Briefly summarize what this tutorial discusses:-Create custom errors with ' New ' function-use ' ERROR ' to add more error information-use struct type and field to provide more error information-use struct type and method to provide more error information I wish you a happy life. * * Previous tutorial-[Error handling] (https://studygolang.com/articles/12724) * * * * Next tutorial-[Panic and recover] (https://studygolang.com/articles /12785) * *

via:https://golangbot.com/custom-errors/

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

1607 Reads
Related Article

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.