Movatterモバイル変換


[0]ホーム

URL:


  1. Documentation
  2. Tutorials
  3. Return and handle an error

Return and handle an error

Handling errors is an essential feature of solid code. In this section, you'll add a bit of code to return an error from the greetings module, then handle it in the caller.

Note: This topic is part of a multi-part tutorial that begins withCreate a Go module.
  1. In greetings/greetings.go, add the code highlighted below.

    There's no sense sending a greeting back if you don't know who to greet. Return an error to the caller if the name is empty. Copy the following code into greetings.go and save the file.

    package greetingsimport ("errors"    "fmt")// Hello returns a greeting for the named person.func Hello(name string)(string, error) {// If no name was given, return an error with a message.    if name == "" {        return "", errors.New("empty name")    }    // If a name was received, return a value that embeds the name    // in a greeting message.    message := fmt.Sprintf("Hi, %v. Welcome!", name)    return message, nil}

    In this code, you:

    • Change the function so that it returns two values: astring and anerror. Your caller will check the second value to see if an error occurred. (Any Go function can return multiple values. For more, seeEffective Go.)
    • Import the Go standard libraryerrors package so you can use itserrors.New function.
    • Add anif statement to check for an invalid request (an empty string where the name should be) and return an error if the request is invalid. Theerrors.New function returns anerror with your message inside.
    • Addnil (meaning no error) as a second value in the successful return. That way, the caller can see that the function succeeded.
  2. In your hello/hello.go file, handle the error now returned by theHello function, along with the non-error value.

    Paste the following code into hello.go.

    package mainimport (    "fmt""log"    "example.com/greetings")func main() {// Set properties of the predefined Logger, including    // the log entry prefix and a flag to disable printing    // the time, source file, and line number.    log.SetPrefix("greetings: ")    log.SetFlags(0)    // Request a greeting message.message, err := greetings.Hello("")// If an error was returned, print it to the console and    // exit the program.    if err != nil {        log.Fatal(err)    }    // If no error was returned, print the returned message    // to the console.    fmt.Println(message)}

    In this code, you:

    • Configure thelog package to print the command name ("greetings: ") at the start of its log messages, without a time stamp or source file information.
    • Assign both of theHello return values, including theerror, to variables.
    • Change theHello argument from Gladys’s name to an empty string, so you can try out your error-handling code.
    • Look for a non-nilerror value. There's no sense continuing in this case.
    • Use the functions in the standard library'slog package to output error information. If you get an error, you use thelog package'sFatal function to print the error and stop the program.
  3. At the command line in thehello directory, run hello.go to confirm that the code works.

    Now that you're passing in an empty name, you'll get an error.

    $ go run .greetings: empty nameexit status 1

That's common error handling in Go: Return an error as a value so the caller can check for it.

Next, you'll use a Go slice to return a randomly-selected greeting.

< Call your code from another moduleReturn a random greeting >

go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp