R3t*_*rnz 0 error-handling json go
enc := json.NewEncoder(w)
err := enc.Encode(struct {
Method string `json:"method"`
Results []interface{} `json:"results"`
CacheTime int `json:"cache_time"`
}{Method: answerInlineQueryMethod, Results: results, CacheTime: 0})
if err != nil {
log.Printf("failed to answer to inline query: %s", err)
}
Run Code Online (Sandbox Code Playgroud)
我如何区分应该导致恐慌的JSON错误和发送响应导致的错误,哪些应该记录?
该encoding/json包定义了它将返回的错误类型.对于编码你有MarshalerError,
UnsupportedTypeError和UnsupportedValueError.
您可以检查返回的错误类型Encode是否为这些中的一个.
如果响应不是很大并且不依赖于根据json.Encoder协议发送多个json值,则可以json.Marshal单独使用和写入响应.