Error Handling Patterns for JSON Processing
2026-01-30#JSON#Error Handling#JavaScript#Validation
Graceful error handling is crucial for reliable JSON processing. This guide covers patterns for handling errors at every stage.
Error Types
Different errors require different handling:
const JSON_ERRORS = {
SYNTAX_ERROR: 'Invalid JSON syntax',
TYPE_ERROR: 'Type mismatch',
MISSING_FIELD: 'Required field missing',
INVALID_VALUE: 'Invalid field value',
CIRCULAR_REF: 'Circular reference detected',
OVERFLOW_ERROR: 'Value exceeds limits'
};
Try-Catch Patterns
Basic Error Handling
function safeParse(jsonString) {
try {
return { ok: true, data: JSON.parse(jsonString) };
} catch (error) {
return {
ok: false,
error: {
code: 'SYNTAX_ERROR',
message: error.message,
position: findErrorPosition(jsonString, error)
}
};
}
}
Detailed Position Finding
function findErrorPosition(jsonString, error) {
const match = error.message.match(/position (\d+)/);
if (match) {
const pos = parseInt(match[1], 10);
const lineNumber = jsonString.slice(0, pos).split('\n').length;
const column = pos - jsonString.slice(0, pos).lastIndexOf('\n');
return { line: lineNumber, column, character: pos };
}
return null;
}
Validation Error Reporting
Structured Error Details
function validateUser(data) {
const errors = [];
if (!data.email) {
errors.push({
field: 'email',
code: 'REQUIRED',
message: 'Email is required'
});
} else if (!isValidEmail(data.email)) {
errors.push({
field: 'email',
code: 'INVALID_FORMAT',
message: 'Invalid email format'
});
}
if (data.age !== undefined && (typeof data.age !== 'number' || data.age < 0)) {
errors.push({
field: 'age',
code: 'INVALID_RANGE',
message: 'Age must be a non-negative number'
});
}
return {
valid: errors.length === 0,
errors
};
}
Error Response Format
{
"success": false,
"error": {
"code": "VALIDATION_FAILED",
"message": "Request validation failed",
"details": [
{
"field": "email",
"code": "REQUIRED",
"message": "Email is required"
},
{
"field": "age",
"code": "INVALID_RANGE",
"message": "Age must be between 0 and 150",
"received": -5
}
]
}
}
Recovery Strategies
Default Values
function parseWithDefaults(jsonString, defaults) {
try {
const data = JSON.parse(jsonString);
return { ...defaults, ...data };
} catch (error) {
return defaults;
}
}
const config = parseWithDefaults(userInput, {
theme: 'light',
language: 'en',
notifications: true
});
Partial Parsing
function parsePartial(jsonString, requiredFields) {
try {
const data = JSON.parse(jsonString);
const missing = requiredFields.filter(field => data[field] === undefined);
if (missing.length > 0) {
return {
ok: false,
partial: data,
missing
};
}
return { ok: true, data };
} catch (error) {
return { ok: false, error: error.message };
}
}
Graceful Degradation
async function processWithFallback(input) {
try {
// Try primary processing
return await primaryProcessing(input);
} catch (error) {
if (error.code === 'SYNTAX_ERROR') {
// Try to extract valid portion
return await extractValidData(input);
}
if (error.code === 'TIMEOUT') {
// Use cached result
return await getCachedResult(input);
}
throw error;
}
}
Circular Reference Handling
Detection
function hasCircularReference(obj) {
const seen = new WeakSet();
function traverse(value) {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return true;
seen.add(value);
for (const key in value) {
if (traverse(value[key])) return true;
}
}
return false;
}
return traverse(obj);
}
Safe Serialization
function safeStringify(obj, maxDepth = 10) {
const seen = new Map();
function replacer(key, value) {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return { __circular_ref__: true };
}
seen.set(value, true);
}
return value;
}
return JSON.stringify(obj, replacer);
}
Async Error Boundaries
async function processJsonQueue(queue) {
const results = [];
const errors = [];
for (const item of queue) {
try {
const result = await processItem(item);
results.push(result);
} catch (error) {
errors.push({
item,
error: error.message,
code: error.code
});
}
}
return { processed: results.length, failed: errors.length, errors };
}
Logging and Monitoring
Structured Logging
function logJsonError(context, error, payload) {
logger.error('JSON Processing Error', {
context,
errorCode: error.code,
errorMessage: error.message,
errorPosition: error.position,
payloadSnippet: payload?.slice(0, 100),
timestamp: new Date().toISOString(),
requestId: context.requestId
});
}
Error Metrics
Track error rates:
const errorMetrics = {
syntaxErrors: 0,
validationErrors: 0,
circularRefs: 0,
increment(type) {
this[type]++;
metricsClient.gauge(`json.errors.${type}`, this[type]);
}
};
User-Friendly Messages
Provide helpful error messages:
| Error | Technical | User-Friendly |
|---|---|---|
| Syntax | Unexpected token at position 15 |
Check your JSON format. Example: {"name": "John"} |
| Type | Expected number, got string |
The "age" field should be a number, not text |
| Validation | Pattern mismatch |
Phone number should be 10 digits |
Summary
Handle JSON errors by: categorizing error types, providing structured details, offering recovery options, logging systematically, and showing user-friendly messages.
Related articles
Working with Large JSON Files - A Practical Guide
Techniques and tools for handling JSON files that exceed memory limits or browser constraints.
JSON vs XML - Choosing the Right Format for Your Use Case
A comprehensive comparison of JSON and XML to help you make informed format decisions.
JSON Tools Ecosystem - A Comprehensive Overview
Explore the best tools, libraries, and utilities for working with JSON across different platforms and use cases.
JSON Security Best Practices - Protecting Your Applications
Essential security measures for handling JSON data safely and preventing common vulnerabilities.
Understanding JSON Schema - A Complete Guide
Learn how to define and validate JSON structure with JSON Schema, from basics to advanced features.
JSON Performance Optimization Techniques
Speed up JSON parsing, serialization, and processing with these proven optimization strategies.