How do you Handle Errors During JSON Marshalling in Golang?

Linda Hamilton
Release: 2024-10-30 17:19:25
Original
681 people have browsed it

How do you Handle Errors During JSON Marshalling in Golang?

Error Handling in Golang JSON Marshalling

JSON data structures cannot represent cyclic references, and Go's json.Marshal function cannot handle them. As a result, passing cyclic structures to Marshal leads to an infinite recursion and a runtime panic.

Beyond cyclic structures, json.Marshal can also return non-nil errors in situations where it encounters unsupported types or invalid values.

Unsupported Types

Marshal returns an UnsupportedTypeError when attempting to marshal an unsupported data type. For example:

<code class="go">import "encoding/json"

func main() {
    ch := make(chan int)
    _, err := json.Marshal(ch)
    if _, ok := err.(*json.UnsupportedTypeError); ok {
        // Error: Unmarshal: unsupported type: chan int
    }
}</code>
Copy after login

Unsupported Values

Marshal can also return an UnsupportedValueError when attempting to marshal an invalid value. For instance:

<code class="go">import (
    "encoding/json"
    "math"
)

func main() {
    positiveInfinity := math.Inf(1)
    _, err := json.Marshal(positiveInfinity)
    if _, ok := err.(*json.UnsupportedValueError); ok {
        // Error: json: unsupported value: +Inf
    }
}</code>
Copy after login

By understanding these conditions, developers can handle errors gracefully and ensure that json.Marshal returns the expected results or handle the appropriate errors.

The above is the detailed content of How do you Handle Errors During JSON Marshalling in Golang?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!