Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get error as string from error interface

Tags:

go

How to get error as string from an error interface?

I want to assign ERROR: Fake error! to a variable and then convert it to a slice []byte(error_str)

prefix_err := "ERROR: "

defer func() {
    if err := recover(); err != nil {
        // get error message from "err" as string
    }
}()

panic("Fake error!")
like image 751
clarkk Avatar asked Jan 20 '26 11:01

clarkk


1 Answers

There are two different problems here:

The first problem: The actual error type is actually a built-in interface. To implement it you implement a method on the type func Error() string. So anything with the error type can be converted to a string format by calling its Error function.

The second problem: panic doesn't take in an error, it takes in an interface{}. The recover builtin similarly returns whatever interface{} you passed to panic. In this case, calling Error won't work. Indeed, you didn't pass an error into panic, you passed in a string (which is common).

There are a lot of ways you can get a string from an interface{}, and a big type switch is one. But overall I think the easiest option is

myBytes := []byte(fmt.Sprintf("%s%v", prefix_err, err))

Which will always get a string representation of whatever the interface{} was, calling String() or Error() as necessary, and then convert it into a []byte.

(Minor footnote: it's not considered Go style to use underscores in variable names, use camelCase instead).

Edit:

Since it turns out we had a partial "X Y problem" with the conversion to a []byte to write into an io.Writer. If you want to log this to Stderr, you can instead use fmt.Fprintf(os.Stderr, "%s%v\n", prefix_err, err) or even fmt.Fprintln(os.Stderr, prefix_err, err). Any Fprint will correctly print to any io.Writer, including a logfile.

like image 62
Linear Avatar answered Jan 22 '26 18:01

Linear