KB Home

Best Practices for Error Handling

On this page Core Principles Common Patterns Code Examples Monitoring & Reporting Further Resources

Core Principles

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

Further Resources