Home  >  Article  >  Backend Development  >  When Does `json.Marshal` Return a Non-Panic Error?

When Does `json.Marshal` Return a Non-Panic Error?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 06:34:31188browse

When Does `json.Marshal` Return a Non-Panic Error?

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:

  • UnsupportedTypeError: Occurs when an invalid type is passed, such as a channel or function.
  • UnsupportedValueError: Raised when an invalid value is provided, such as infinity.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn