json.Marshal Error Handling: Understanding Input Induced Errors
The json.Marshal function, as highlighted in the documentation, fails to handle cyclic data structures, leading to runtime panics. While this is a common scenario, it is possible to encounter situations where a non-panic error is generated instead.
Input Causing Error Generation
To illustrate a non-panic scenario, consider the following example:
<code class="go">type Node struct { Value int Next *Node } func main() { node1 := Node{1, nil} node2 := Node{2, &node1} node1.Next = &node2 _, err := json.Marshal(node1) if err != nil { fmt.Printf("Error encountered: %v\n", err) } }</code>
Result:
The above program will execute without panicking and instead return the error: json: unsupported type: *main.Node
Error Types
The json.Marshal function can generate two types of errors:
In the given example, the error falls into the UnsupportedValueError category, as it pertains to an invalid value (cyclic data structure) rather than an invalid type.
Additional Examples:
Here are some additional scenarios that can cause json.Marshal to return non-nil errors:
<code class="go">_, err := json.Marshal(nil) // Error: json: unsupported value: nil _, err := json.Marshal(1e100) // Error: json: unsupported value: 1e+100, must be finite</code>
The above is the detailed content of When Does `json.Marshal` Return a Non-Panic Error?. For more information, please follow other related articles on the PHP Chinese website!