error handling - In Go, can JSON marshaling of a well-defined type ever fail? -
given following code:
package main import ( "encoding/json" "fmt" "log" ) type employee struct { id int "json:id" } func main() { b, err := json.marshal(&employee{id: 2}) if err != nil { log.fatal("couldn't marshal employee") } fmt.println(string(b)) }
can checking error reliably ignored using _
placeholder since employee
struct defined. theoretically should never fail, begs question practice ignore type of error , save little on type of boilerplate error checking?
ignoring so:
package main import ( "encoding/json" "fmt" ) type employee struct { id int "json:id" } func main() { b, _ := json.marshal(&employee{id: 2}) fmt.println(string(b)) }
proper error handling essential requirement of software.
normally code won't fail. if user adds marshaljson
method reciver type, fails:
func (t *employee) marshaljson() ([]byte, error) { if t.id == 2 { return nil, fmt.errorf("forbiden id = %d", t.id) } data := []byte(fmt.sprintf(`{"id":%d}`, t.id)) return data, nil }
this code compiles, fails on purpose id == 2
(the go playground):
package main import ( "encoding/json" "fmt" "log" ) type employee struct { id int "json:id" } func main() { b, err := json.marshal(&employee{id: 2}) if err != nil { log.fatal("couldn't marshal employee", err) } fmt.println(string(b)) } func (t *employee) marshaljson() ([]byte, error) { if t.id == 2 { return nil, fmt.errorf("forbiden id = %d", t.id) } data := []byte(fmt.sprintf(`{"id":%d}`, t.id)) return data, nil }
also code compiles, fails (the go playground):
package main import ( "encoding/json" "fmt" "log" ) type employee struct { id int "json:id" } func main() { b, err := json.marshal(&employee{id: 2}) if err != nil { log.fatal("couldn't marshal employee") } fmt.println(string(b)) } func (t employee) marshaljson() ([]byte, error) { data := []byte(fmt.sprint(t)) return data, nil }
Comments
Post a Comment