Skip to content

Instantly share code, notes, and snippets.

@zianwar
Last active October 29, 2021 10:19
Show Gist options
  • Save zianwar/a8c9e1d6b86791a41fc1332aa4ffb72b to your computer and use it in GitHub Desktop.
Save zianwar/a8c9e1d6b86791a41fc1332aa4ffb72b to your computer and use it in GitHub Desktop.
Golang JSON Syntax error handling
package main
import (
"encoding/json"
"fmt"
"log"
)
type SyntaxError struct {
*json.SyntaxError
input []byte
}
func (e SyntaxError) Error() string {
return fmt.Sprintf("syntax error near: `%s`", string(e.input[e.Offset-1:]))
}
func unmarshal(data []byte, v interface{}) error {
err := json.Unmarshal(data, &v)
if e, ok := err.(*json.SyntaxError); ok {
return SyntaxError{e, data}
}
return err
}
func main() {
input := []byte(`{ "name": Anwar" }`)
var v interface{}
log.Fatal(unmarshal(input, &v)) // syntax error near: `Anwar" }`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment