---
name: js-ts-error-handling
description: "Best practices for error handling in JS/TS using try/catch, custom errors, and global handlers."
language: js-ts
---

# JS/TS Error Handling

Robust error handling patterns in JavaScript and TypeScript for reliable applications.

## Guidelines
- **Use `try/catch` with `async/await`**: Ensure all asynchronous operations are wrapped in error handling blocks.
- **Throw `Error` objects**: Never throw strings or other primitives. Always throw an instance of `Error` or a custom subclass.
- **Custom Error Classes**: Define specific error classes (e.g., `ValidationError`, `NotFoundError`) for better error categorization and handling.
- **Centralized Error Handling**: In Node.js/Express, use error-handling middleware. In React, use Error Boundaries.
- **Provide Context**: Include relevant details in error objects (e.g., status codes, input data).
- **Graceful Degradation**: Ensure the UI remains functional or provides a clear message when an error occurs.
- **Log Errors Securely**: Log errors for debugging but avoid exposing sensitive information to the end-user.

## Tools & Libraries
- **Standard `Error` class**: The base for all errors.
- **ts-results / fp-ts**: For functional error handling patterns (Result/Either).
- **Sentry / LogRocket**: For frontend and backend error tracking and reporting.

## Trigger Scenarios
- When an API call can fail.
- When validating user input.
- When implementing a global error handler for a web application.
- When debugging "uncaught promise rejection" warnings.

<!-- synapsis-dsai-managed -->
