rakesh
(Rakesh Nayak)
1
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.
skillian
(Sean Killian)
2
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, ¬Found)) // prints true
fmt.Println(notFound, err) // now notFound has the original errMessage
}
func test() error {
err := NotFoundError{errMessage: "Not Found"}
return err
}
1 Like