npm package: @salespark/error-handler
Description: Helper for error capture and handling with Sentry.
Author: SalesPark
Latest version: 1.0.6

> **npm registry notice:** On **2 May 2026** (timezone **Europe/Lisbon**), this package will no longer be **publicly** installable from the npm registry and will become **restricted to the SalesPark npm organization**. Until then, already-published versions remain public. **No further public releases** or support for external consumers is planned — if you depend on this package, **fork** before that date.

## @salespark/error-handler

Sentry-focused helper for error capture and reporting in Node.js.  
Includes log levels, safe request error parsing, optional metrics, and global configuration.

---

## 📦 Installation

```bash
yarn add @salespark/error-handler
# or
npm i @salespark/error-handler
```

Supports **CommonJS** and **ESM**.

```ts
// ESM
import {
  debug,
  info,
  warning,
  error,
  critical,
  parseRequestError,
  setMetricReporter,
  setLogLimits,
  setEnvironment,
  setNotificationsEnabled,
  setTags,
  setContext,
  setUser,
  setCleanupHandler,
} from "@salespark/error-handler";

// CommonJS
const {
  debug,
  info,
  warning,
  error,
  critical,
  parseRequestError,
  setMetricReporter,
  setLogLimits,
  setEnvironment,
  setNotificationsEnabled,
  setTags,
  setContext,
  setUser,
  setCleanupHandler,
} = require("@salespark/error-handler");
```

---

## ⚙️ Configuration

### Environment variables

- `ENVIRONMENT` (default: `DEVELOPMENT`) — used for Sentry tags and console logging.
- `NOTIFICATIONS` (default: `true`) — enable/disable logging.

### Runtime setters

#### `setEnvironment(env: string)`

Override environment at runtime (useful for tests).

```ts
setEnvironment("STAGING");
```

#### `setNotificationsEnabled(enabled: boolean)`

Enable or disable logging at runtime.

```ts
setNotificationsEnabled(true);
```

#### `setTags(tags: Record<string, string>)`

Global Sentry tags applied to every event.

```ts
setTags({ service: "billing", region: "eu" });
```

#### `setContext(key: string, value: unknown)`

Add global Sentry context.

```ts
setContext("featureFlags", { newCheckout: true });
```

#### `setUser(user: Record<string, unknown> | null)`

Attach user metadata to events.

```ts
setUser({ id: "123", email: "user@salespark.com" });
```

#### `setMetricReporter(fn: (name: string, value: number) => void)`

Inject a metrics reporter (Prometheus, Datadog, etc.).

```ts
setMetricReporter((name, value) => {
  console.log("metric", name, value);
});
```

#### `setLogLimits(maxPathLength?: number, maxPayloadLength?: number)`

Adjust truncation limits for locations and string payloads.

```ts
setLogLimits(160, 8000);
```

#### `setCleanupHandler(fn: (() => void) | null)`

Override cleanup logic (executed on `beforeExit`, `SIGINT`, `SIGTERM`, `exit`).

```ts
setCleanupHandler(() => {
  // close resources, flush, etc
});
```

---

## ✨ API

### Loggers

- `debug(message, location?, extra?)`
- `info(message, location?, extra?)`
- `warning(message, location?, extra?)`
- `error(message, location?, extra?)`
- `critical(message, location?, extra?)`
- `cleanup()`
- `errorHandler(req, res, next)`

```ts
info("Service started", "bootstrap");
warning("Slow response", "orders/list", { ms: 1200 });
error(new Error("DB timeout"));
```

```ts
// Express middleware
app.use(errorHandler);
```

### `parseRequestError(err)`

Normalizes HTTP client errors (axios/fetch/custom) into a safe object.

```ts
const parsed = parseRequestError(err);
// { status, statusText, data, stack, originalError }
```

---

## 🔍 Behavior notes

- In `DEVELOPMENT`, it also logs to console with timestamps.
- When `NOTIFICATIONS=false`, logging is skipped.
- If Sentry is not initialized, it logs to console and emits a warning.

---

## 🧪 Examples

### ESM (destructuring)

```ts
import * as Sentry from "@sentry/node";
import { error, critical, setEnvironment, setTags, setContext, setUser, setMetricReporter } from "@salespark/error-handler";

// Initialize Sentry
Sentry.init({ dsn: process.env.SENTRY_DSN });

setEnvironment("PRODUCTION");
setTags({ service: "api", region: "eu" });
setContext("build", { version: "1.2.3" });
setUser({ id: "42", email: "user@salespark.com" });
setMetricReporter((name, value) => {
  console.log("metric", name, value);
});

error(new Error("Something failed"));
critical(new Error("Outage!"), "payments/service");
```

```ts
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    error(err, "/helpers/somefile.js/catch");
  }
};

run();
```

### ESM (no destructuring)

```ts
import * as Sentry from "@sentry/node";
import * as errorCapture from "@salespark/error-handler";

// Initialize Sentry
Sentry.init({ dsn: process.env.SENTRY_DSN });

errorCapture.setEnvironment("PRODUCTION");
errorCapture.setTags({ service: "api", region: "eu" });
errorCapture.setContext("build", { version: "1.2.3" });
errorCapture.setUser({ id: "42", email: "user@salespark.com" });
errorCapture.setMetricReporter((name, value) => {
  console.log("metric", name, value);
});

errorCapture.error(new Error("Something failed"));
errorCapture.critical(new Error("Outage!"), "payments/service");
```

```ts
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    errorCapture.error(err, "/helpers/somefile.js/catch");
  }
};

run();
```

### CommonJS (destructuring)

```ts
const Sentry = require("@sentry/node");
const { error, critical, setEnvironment, setTags, setContext, setUser, setMetricReporter } = require("@salespark/error-handler");

// Initialize Sentry
Sentry.init({ dsn: process.env.SENTRY_DSN });

setEnvironment("PRODUCTION");
setTags({ service: "api", region: "eu" });
setContext("build", { version: "1.2.3" });
setUser({ id: "42", email: "user@salespark.com" });
setMetricReporter((name, value) => {
  console.log("metric", name, value);
});

error(new Error("Something failed"));
critical(new Error("Outage!"), "payments/service");
```

```ts
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    error(err, "/helpers/somefile.js/catch");
  }
};

run();
```

### CommonJS (no destructuring)

```ts
const Sentry = require("@sentry/node");
const errorCapture = require("@salespark/error-handler");

// Initialize Sentry
Sentry.init({ dsn: process.env.SENTRY_DSN });

errorCapture.setEnvironment("PRODUCTION");
errorCapture.setTags({ service: "api", region: "eu" });
errorCapture.setContext("build", { version: "1.2.3" });
errorCapture.setUser({ id: "42", email: "user@salespark.com" });
errorCapture.setMetricReporter((name, value) => {
  console.log("metric", name, value);
});

errorCapture.error(new Error("Something failed"));
errorCapture.critical(new Error("Outage!"), "payments/service");
```

```ts
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    errorCapture.error(err, "/routes/acme/operations.js/someFunction/catch");
    return { status: false, data: { message: "Failed to do something...", code: "someErrorCode" } };
  }
};

run();
```

---

### 🔒 Internal Usage Notice

This package is primarily designed and maintained for internal use within the SalesPark ecosystem.
While it can technically be used in other Node.js projects, no official support or guarantees are provided outside of SalesPark-managed projects.

All code follows the same engineering standards applied across the SalesPark platform, ensuring consistency, reliability, and long-term maintainability of our internal systems.

⚡ Note: This package is most efficient and works best when used together with other official SalesPark packages, where interoperability and optimizations are fully leveraged.

Disclaimer: This software is provided "as is", without warranties of any kind, express or implied. SalesPark shall not be held liable for any issues, damages, or losses arising from its use outside the intended SalesPark environment.

Organization packages: https://www.npmjs.com/org/salespark

---

## 📄 License

## MIT © [SalesPark](https://salespark.io)

_Document version: 2_  
_Last update: 04-04-2026_