Chapter 13: Error Handling
Chapter 13 of 15
Chapter 13: Error Handling
13.1 Error Management
Comprehensive error handling ensures applications fail gracefully and provide useful feedback.
// Global error handler
app.use((err, req, res, next) => {
console.error(err.stack);
// Log to error tracking service
errorTracker.captureException(err);
// Send appropriate response
res.status(err.statusCode || 500).json({
success: false,
error: {
message: err.message || 'Internal server error',
...(process.env.NODE_ENV === 'development' && { stack: err.stack })
}
});
});
13.2 Frontend Error Boundaries
// React error boundary
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught:', error, errorInfo);
// Send to error tracking
}
render() {
if (this.state.hasError) {
return <ErrorFallback error={this.state.error} />;
}
return this.props.children;
}
}
13.3 API Error Handling
// Consistent error responses
function handleError(err, req, res, next) {
if (err.name === 'ValidationError') {
return res.status(400).json({
success: false,
error: { message: err.message, code: 'VALIDATION_ERROR' }
});
}
if (err.name === 'UnauthorizedError') {
return res.status(401).json({
success: false,
error: { message: 'Unauthorized', code: 'UNAUTHORIZED' }
});
}
// Default error
res.status(500).json({
success: false,
error: { message: 'Internal server error', code: 'INTERNAL_ERROR' }
});
}