Home  >  Article  >  Backend Development  >  How to Handle JSON Marshal Errors in Go?

How to Handle JSON Marshal Errors in Go?

DDD
DDDOriginal
2024-11-01 08:34:30436browse

How to Handle JSON Marshal Errors in Go?

JSON Marshal Error Handling in Go

When using the json.Marshal function in Go, it's crucial to consider input data that can trigger an error. As mentioned in the official documentation, cyclic data structures are not supported and attempting to marshal them leads to infinite recursion, ultimately resulting in a runtime panic.

To demonstrate a non-panic error condition, let's create a program that showcases two types of errors that json.Marshal can return: UnsupportedTypeError and UnsupportedValueError.

<code class="go">package main

import (
    "encoding/json"
    "fmt"
    "math"
)

func main() {
    // UnsupportedTypeError: marshalling an invalid type (channel)

    ch := make(chan int)
    _, err := json.Marshal(ch)
    if e, ok := err.(*json.UnsupportedTypeError); ok { // Check for specific error type
        fmt.Println("UnsupportedTypeError:", e.Type)
    } else {
        fmt.Println("Error:", err)
    }

    // UnsupportedValueError: marshalling an invalid value (infinity)

    inf := math.Inf(1)
    _, err = json.Marshal(inf)
    if e, ok := err.(*json.UnsupportedValueError); ok { // Check for specific error type
        fmt.Println("UnsupportedValueError:", e.Value)
    } else {
        fmt.Println("Error:", err)
    }
}</code>

Output:

UnsupportedTypeError: chan int
UnsupportedValueError: +Inf

By providing specific inputs, this program demonstrates that json.Marshal can return non-nil errors without causing a panic. This allows developers to handle these errors gracefully in their applications.

The above is the detailed content of How to Handle JSON Marshal Errors in Go?. 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