当我有一个错误结构,其中包含嵌套在错误中的切片时。Is 似乎无法正常工作:
package main
import (
"errors"
"fmt"
"os"
)
type Response struct {
Details []string
}
type ErrResponseError struct {
Response Response
}
func (err ErrResponseError) Error() string {
return "response error"
}
func main() {
err := ErrResponseError{}
fmt.Fprintf(os.Stdout, "equal: %v", errors.Is(err, ErrResponseError{}))
}
退货
等于:假
package main
import (
"errors"
"fmt"
"os"
)
type Response struct {
Details string // Changed this line
}
type ErrResponseError struct {
Response Response
}
func (err ErrResponseError) Error() string {
return "response error"
}
func main() {
err := ErrResponseError{}
fmt.Fprintf(os.Stdout, "equal: %v", errors.Is(err, ErrResponseError{}))
}
退货
等于:真
................................................ ...................................................... ...................................................... ...................................................... ................................................
来自文档:
如果错误等于目标或者实现 Is(error) bool 方法使得 Is(target) 返回 true,则认为错误与目标匹配。
因此,您可以通过编写一个比较两个切片的
Is
方法来做到这一点。
默认的误差比较算法检查误差是否等于目标。由于您的错误包含一个切片,因此无法比较。