Tuesday, July 2, 2024
HomeGolangCustomized Error comparability fails - Getting Assist

Customized Error comparability fails – Getting Assist


kind NotFoundError struct {
    errMessage string
}

func (n NotFoundError) Error() string {
    return n.errMessage
}

func primary() {
    err := check()
    var notFound NotFoundError
    fmt.Println(errors.Is(err, notFound)) // prints false
    fmt.Println(err)
}

func check() error {
    err := NotFoundError{errMessage: "Not Discovered"}
    return err
}

Hello all, fmt.Println(errors.Is(err, notFound)) prints false. Please somebody assist me perceive why it’s occurring.

As a result of NotFoundError{errMessage: "Not Discovered"} != NotFoundError{}.

You can use errors.As as a substitute and you’re going to get true:

package deal primary

import (
	"errors"
	"fmt"
)

kind NotFoundError struct {
	errMessage string
}

func (n NotFoundError) Error() string {
	return n.errMessage
}

func primary() {
	err := check()
	var notFound NotFoundError
	fmt.Println(errors.As(err, &notFound)) // prints true
	fmt.Println(notFound, err) // now notFound has the unique errMessage
}

func check() error {
	err := NotFoundError{errMessage: "Not Discovered"}
	return err
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments