dragam0217 2014-09-27 19:49
浏览 13
已采纳

从错误界面以字符串形式获取错误

How to get error as string from an error interface?

I want to assign ERROR: Fake error! to a variable and then convert it to a slice []byte(error_str)

prefix_err := "ERROR: "

defer func() {
    if err := recover(); err != nil {
        // get error message from "err" as string
    }
}()

panic("Fake error!")
  • 写回答

2条回答 默认 最新

  • douzhonglong3789 2014-09-27 19:56
    关注

    There are two different problems here:

    The first problem: The actual error type is actually a built-in interface. To implement it you implement a method on the type func Error() string. So anything with the error type can be converted to a string format by calling its Error function.

    The second problem: panic doesn't take in an error, it takes in an interface{}. The recover builtin similarly returns whatever interface{} you passed to panic. In this case, calling Error won't work. Indeed, you didn't pass an error into panic, you passed in a string (which is common).

    There are a lot of ways you can get a string from an interface{}, and a big type switch is one. But overall I think the easiest option is

    myBytes := []byte(fmt.Sprintf("%s%v", prefix_err, err))
    

    Which will always get a string representation of whatever the interface{} was, calling String() or Error() as necessary, and then convert it into a []byte.

    (Minor footnote: it's not considered Go style to use underscores in variable names, use camelCase instead).

    Edit:

    Since it turns out we had a partial "X Y problem" with the conversion to a []byte to write into an io.Writer. If you want to log this to Stderr, you can instead use fmt.Fprintf(os.Stderr, "%s%v ", prefix_err, err) or even fmt.Fprintln(os.Stderr, prefix_err, err). Any Fprint will correctly print to any io.Writer, including a logfile.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作