Struct as a return value in Error()

Hi,

I have defined a custom error which implements error interface. But I want to return a struct instead of string for Error() function. Is that possible or Is there any so that I can use the status code and error msg returned by function.
Example:-

package main

import (
    "errors"
    "fmt"
    "os"
)

type RequestError struct {
    StatusCode int

    Msg string
}

func (r *RequestError) Error() string {
    return fmt.Sprintf("status %d: err %s", r.StatusCode, r.Msg)
}

func doRequest() error {
    return &RequestError{
        StatusCode: 503,
        Msg:        "unavailable",
    }
}

func main() {
    err := doRequest()
    if err != nil {
        fmt.Println(err)
       // fmt.Println(err.StatusCode)
       // fmt.Println(err.Msg)
        os.Exit(1)
    }
    fmt.Println("success!")
}

Like what ever I have added as a comment in main function.

Is this possible?

Thanks in Advance

The Err field is missing in the struct:

package main

import (
	"fmt"
	"os"
)

type RequestError struct {
	StatusCode int
	Msg        string
	Err        string
}

func (r *RequestError) Error() string {
	return fmt.Sprintf("status %d: err %s", r.StatusCode, r.Msg)
}

func doRequest() error {
	return &RequestError{
		StatusCode: 503,
		Err:        "unavailable",
	}
}

func main() {
	err := doRequest()
	if err != nil {
		fmt.Println(err)
		// fmt.Println(err.StatusCode)
		// fmt.Println(err.Msg)
		os.Exit(1)
	}
	fmt.Println("success!")
}

No, the error interface is:

type error interface {
    Error() string
}

If you return something that is not a string, your custom error will no longer be considered an error because the signature doesn’t match.

Why do you want to return something that’s not a string from your Error function?

EDIT: I bumped Save :slight_smile:

You should change your main function to do this:

	if err != nil {
		fmt.Println(err)
		if re, ok := err.(*RequestError); ok {
			fmt.Println(re.StatusCode)
			fmt.Println(re.Msg)
		}
		os.Exit(1)
	}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.