本文介绍了什么输入会导致golang的json.Marshal返回一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自:

我遇到过这种情况,这会导致运行时恐慌。 / p>

我想知道的是,如果任何人都可以提供一个工作程序来演示json.Marshal返回非零错误的非紧急情况。最好的答案是显然包括使用的输入。

解决方案

为了补充Jonathan的回答,json .Marshal函数可以返回两种类型的错误: UnsupportedTypeError UnsupportedValueError



第一个是可能造成的,正如Jonathan所说,试图对一个无效类型进行编组:

  _,err: = json.Marshal(make(chan int))
_,ok:= err。(* json.UnsupportedTypeError)// ok == true

另一方面,您也可以通过传递无效值来使Marshal函数返回错误:

  _,err:= json.Marshal(math.Inf(1))
_,ok:= err。(* json.UnsupportedValueError)// ok == true


From the docs:

I've experienced this situation, which results in a runtime panic.

What I'm wondering is if anyone can provide a working program that demonstrates a non-panic situation where json.Marshal returns a non-nil error. The best answers would clearly include the inputs used.

解决方案

Just to complement Jonathan's answer, the json.Marshal function can return two types of errors: UnsupportedTypeError or UnsupportedValueError

The first one can be caused, as Jonathan said by trying to Marshal an invalid type:

_, err := json.Marshal(make(chan int))
_, ok := err.(*json.UnsupportedTypeError) // ok == true

On the other hand you can also have the Marshal function return an error by passing an invalid value:

_, err := json.Marshal(math.Inf(1))
_, ok := err.(*json.UnsupportedValueError) // ok == true

这篇关于什么输入会导致golang的json.Marshal返回一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 10:20