Last active
October 29, 2021 10:19
-
-
Save zianwar/a8c9e1d6b86791a41fc1332aa4ffb72b to your computer and use it in GitHub Desktop.
Golang JSON Syntax error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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