Best Practices for Error Handling
Core Principles
- Fail fast, fail early: Detect errors as close to the source as possible.
- Provide context: Include relevant data without exposing sensitive info.
- Consistent format: Use a unified error schema (code, message, details).
- Graceful degradation: Offer fallback behavior for nonâcritical failures.
- Security first: Never leak stack traces or internal IDs to end users.
Common Patterns
Exception Wrapping
Wrap lowâlevel exceptions in domainâspecific ones to add meaning.
class ServiceError extends Error {
constructor(message, cause) {
super(message);
this.name = 'ServiceError';
this.cause = cause;
}
}
Result Objects
Return a result object instead of throwing when failures are expected.
function parseJson(str) {
try {
return { ok: true, data: JSON.parse(str) };
} catch (e) {
return { ok: false, error: 'Invalid JSON', details: e.message };
}
}
Global Error Handler
Centralize uncaught errors for logging and user feedback.
window.addEventListener('error', (e) => {
sendToLoggingService(e.error);
alert('Something went wrong. Please try again.');
});
Code Examples
Node.js Express Middleware
const errorHandler = (err, req, res, next) => {
const status = err.status || 500;
const response = {
code: err.code || 'INTERNAL_ERROR',
message: err.message,
...(process.env.NODE_ENV !== 'production' && { stack: err.stack })
};
res.status(status).json(response);
};
app.use(errorHandler);
React Error Boundary
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
componentDidCatch(error, info) {
logErrorToService(error, info);
}
render() {
return this.state.hasError
? Something went wrong.
: this.props.children;
}
}
fetch('/api/data')
.then(r => {
if (!r.ok) throw new Error('Network response was not ok');
return r.json();
})
.catch(err => {
console.error('Fetch error:', err);
// show user-friendly message
});
Monitoring & Reporting
- Aggregate errors by
code
andendpoint
. - Set alert thresholds for spike detection.
- Correlate with request IDs for traceability.