简体   繁体   English

如何序列化和反序列化 go 中的错误字符串

[英]How to serialize and deserialize errors string in go

In the context of two go services sharing the same types, one client post a json to a server:在两个 go 服务共享相同类型的上下文中,一个客户端向服务器发送一个 json:

type Message struct {
   Error string `json:"error"`
}

The client should serialize an error into a string.客户端应将error序列化为字符串。

The server should deserialize that string into an error on which I can use errors.As or errors.Is to check for wrapped errors and such.服务器应该将该字符串反序列化为一个error ,我可以在该错误上使用errors.Aserrors.Is检查包装错误等。

How may I serialize nested errors?如何序列化嵌套错误?

Let me share with you some thoughts that maybe can guide you in the right direction.让我与您分享一些想法,也许可以指导您朝着正确的方向前进。

errors.Is and errors.As errors.Iserrors.As

These two operators deal with the error type.这两个运算符处理error类型。 The common scenario they are used when you've to deal with an error returned by a function and, based on which type of error it is, take some actions.当您必须处理 function 返回的error并根据错误的类型采取一些操作时,通常会使用它们。 If you're returning just a string from a function, it's almost impossible to invoke errors.Is and errors.As unless you do some extra logic to handle the string.如果您只从 function 返回一个字符串,则几乎不可能调用errors.Iserrors.As ,除非您执行一些额外的逻辑来处理该字符串。

A simple workaround一个简单的解决方法

If you wanna preserve a hierarchical structure for your errors without having to flatten them, you could follow this approach:如果你想为你的错误保留一个层次结构而不必展平它们,你可以遵循这种方法:

package main

import (
    "encoding/json"
    "fmt"
)

type RecursiveErr struct {
    Message string `json:"Message"`
    Err     error  `json:"error"`
}

func (r RecursiveErr) Error() string {
    return r.Message
}

func main() {
    // recursive - marshal
    childErr := RecursiveErr{Message: "leaf-child error"}
    parentErr := RecursiveErr{Message: "root error", Err: &childErr}
    data, _ := json.MarshalIndent(&parentErr, "", "\t")
    fmt.Println(string(data))

    // recursive - unmarshal
    var parsedParentErr RecursiveErr
    json.Unmarshal(data, &parsedParentErr)
    fmt.Println(parsedParentErr.Message)
}

This solution has the following benefits:该解决方案具有以下优点:

  1. You can preserve the hierarchical structure of your errors (parent-child relationship)您可以保留错误的层次结构(父子关系)
  2. You can invoke the errors.Is and errors.As on the Err field.您可以在Err字段上调用errors.Iserrors.As

As it's an uncommon scenario for me, I hope to not be off-topic with your request, let me know!因为这对我来说是一种罕见的情况,所以我希望不要偏离主题,让我知道!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM