Sunday, June 30, 2024
HomeGolangCustomized Error comparability fails - Getting Assist

Customized Error comparability fails – Getting Assist


sort NotFoundError struct {
    errMessage string
}

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

func major() {
    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 would use errors.As as a substitute and you’re going to get true:

package deal major

import (
	"errors"
	"fmt"
)

sort NotFoundError struct {
	errMessage string
}

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

func major() {
	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