不调用Error()方法,如何使用fmt.Print(myError)打印错误信息?

huangapple go评论136阅读模式
英文:

fmt.Print(myError) without implicitly calling Error()?

问题

我想要像fmt.Print()打印其他结构体一样打印我自定义的错误结构体,但是由于它实现了error接口,它只会打印一个字段,即通过Error()方法传递出来的字段。

我该如何做到这一点?

英文:

I want to print everything in my custom error struct like fmt.Print() prints any other struct, but since it implements error it only prints one field, the one I pass out through Error().

How can I do this?

答案1

得分: 2

你可以将error接口断言为你自定义的类型。请注意,最好在这样做时使用“逗号,ok”的习惯用法,否则如果类型断言失败,你的应用程序将会发生恐慌。

package main

import "fmt"

type MyError struct {
    Status  int
    Message string
}

func (e MyError) Error() string {
    return e.Message
}

func BadThing() error {
    return MyError{404, "Not found"}
}

func main() {
    err := BadThing()
    if err != nil {
        if v, ok := err.(MyError); ok {
            fmt.Printf("%+v\n", v.Status) // 或者 v,或者 v.Message,等等。
        }
        fmt.Printf("%v\n", err) // 备用。如果需要,可以将其包装在一个“else”中。
    }
}

Playground - 更多阅读:http://blog.golang.org/error-handling-and-go

英文:

You can type assert the error interface to your custom type. Note that you should, ideally, use the 'comma, ok' idiom when doing so otherwise your application will panic if the type assertion fails.

package main

import "fmt"

type MyError struct {
	Status  int
	Message string
}

func (e MyError) Error() string {
	return e.Message
}

func BadThing() error {
	return MyError{404, "Not found"}
}

func main() {
	err := BadThing()
	if err != nil {
		if v, ok := err.(MyError); ok {
			fmt.Printf("%+v\n", v.Status) // or v, or v.Message, etc.
		}
		fmt.Printf("%v\n", err) // Fallback. Can wrap in this in an 'else' if needed.
	}
}

Playground - and further reading: http://blog.golang.org/error-handling-and-go

huangapple
  • 本文由 发表于 2014年8月6日 07:55:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/25150173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定