Error Handling Strategies
Common JSON Parsing Errors
graph TD
A[JSON Parsing Errors] --> B[Syntax Errors]
A --> C[Type Mismatch]
A --> D[Missing Fields]
A --> E[Unexpected Structures]
Basic Error Checking
Simple Error Handling
func parseJSON(data []byte) {
var result map[string]interface{}
err := json.Unmarshal(data, &result)
if err != nil {
switch {
case errors.Is(err, json.SyntaxError):
log.Println("Invalid JSON syntax")
case errors.Is(err, json.UnmarshalTypeError):
log.Println("Type mismatch error")
default:
log.Println("Parsing error:", err)
}
}
}
Advanced Error Handling Strategies
Error Types Comparison
Error Type |
Description |
Handling Approach |
SyntaxError |
Malformed JSON |
Validate input |
UnmarshalTypeError |
Type conversion issues |
Use type assertions |
InvalidUnmarshalError |
Invalid target for unmarshaling |
Check target type |
Comprehensive Error Handling
func robustJSONParse(data []byte) {
var result map[string]interface{}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.DisallowUnknownFields() // Strict parsing
if err := decoder.Decode(&result); err != nil {
var typeError *json.UnmarshalTypeError
var syntaxError *json.SyntaxError
switch {
case errors.As(err, &typeError):
fmt.Printf("Type error: %v at offset %d\n",
typeError.Field, typeError.Offset)
case errors.As(err, &syntaxError):
fmt.Printf("Syntax error at position %d\n",
syntaxError.Offset)
default:
fmt.Println("Unknown parsing error:", err)
}
}
}
Validation Techniques
Struct Validation
type User struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"email"`
}
func validateUser(data []byte) error {
var user User
if err := json.Unmarshal(data, &user); err != nil {
return err
}
validate := validator.New()
return validate.Struct(user)
}
Error Handling Flow
graph TD
A[JSON Input] --> B{Parse JSON}
B --> |Success| C[Process Data]
B --> |Error| D[Error Handling]
D --> E[Log Error]
D --> F[Provide Fallback]
D --> G[Notify User]
Best Practices
- Always validate JSON before processing
- Use specific error type checking
- Provide meaningful error messages
- Implement graceful error recovery
Note: Enhance your error handling skills with LabEx's advanced Go programming courses.