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

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

Barbara Streisand
Release: 2024-11-01 06:34:31
Original
289 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template