Custom Error comparison fails

type NotFoundError struct {
    errMessage string
}

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

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

func test() error {
    err := NotFoundError{errMessage: "Not Found"}
    return err
}

Hi all, fmt.Println(errors.Is(err, notFound)) prints false. Please someone help me understand why it is happening.

Because NotFoundError{errMessage: "Not Found"} != NotFoundError{}.

You could use errors.As instead and you will get true:

package main

import (
	"errors"
	"fmt"
)

type NotFoundError struct {
	errMessage string
}

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

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

func test() error {
	err := NotFoundError{errMessage: "Not Found"}
	return err
}
1 Like

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