How to Get Error Message in String in Go

Jay Singh Feb 02, 2024
  1. Get Error Message in String Using File Error in Go
  2. Get Error Message in String Using Errorf() in Go
How to Get Error Message in String in Go

Error-values can be kept in variables, supplied as parameters to functions, returned from functions, and so on, just like any other built-in type like int, float64, string, etc.

This tutorial will retrieve an error message as a string in Go.

Get Error Message in String Using File Error in Go

In this example, we’ll attempt to open /test_file.txt. If the file is successfully opened, the Open method will return the file handler, and the error will be nil.

If the file cannot be opened, a non-nil error will be returned.

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Open("/test_file.txt")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(f.Name(), "Filed opened successfully")
}

Output:

open /test_file.txt: no such file or directory

Get Error Message in String Using Errorf() in Go

The fmt.Errorf() method allows us to employ formatting tools to construct meaningful error messages in the Go programming language.

package main

import (
	"fmt"
	"time"
)

func main() {
	err := fmt.Errorf("error occurred at: %v", time.Now())
	fmt.Println("Error:", err)
}

Output:

Error: error occurred at: 2022-03-04 23:00:00 +0000 UTC m=+0.000000001