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:
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
}
}
Unsupported Values
Marshal can also return an UnsupportedValueError when attempting to marshal an invalid value. For instance:
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
}
}
By understanding these conditions, developers can handle errors gracefully and ensure that json.Marshal returns the expected results or handle the appropriate errors.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3