×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to return an error in Golang?

By IncludeHelp Last updated : October 05, 2024

Go - Return and handle an error

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?

In Golang, errors are the last return value and have type error, a built-in interface.

Create an error message

errors.New() is used to construct basic error value with the given error messages.

We can also define custom error messages using the Error() method in Golang.

Syntax

    err_1 := errors.New("Error message_1: ")
    err_2 := errors.New("Error message_2: ")

Create and test an error

you can create and handle errors using the errors.New function from the errors package. This function allows you to create a new error with a specific message.

Example

This Go code defines a function test that returns an integer and an error. If the input value is 0, it returns 0 with a nil error. For any other value, it returns -1 and an error indicating an invalid value. The main function demonstrates these behaviors with two test cases.

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>


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.