Skip to content

FBlade/salespark-error-handler

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

@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

yarn add @salespark/error-handler
# or
npm i @salespark/error-handler

Supports CommonJS and ESM.

// 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).

setEnvironment("STAGING");

setNotificationsEnabled(enabled: boolean)

Enable or disable logging at runtime.

setNotificationsEnabled(true);

setTags(tags: Record<string, string>)

Global Sentry tags applied to every event.

setTags({ service: "billing", region: "eu" });

setContext(key: string, value: unknown)

Add global Sentry context.

setContext("featureFlags", { newCheckout: true });

setUser(user: Record<string, unknown> | null)

Attach user metadata to events.

setUser({ id: "123", email: "user@salespark.com" });

setMetricReporter(fn: (name: string, value: number) => void)

Inject a metrics reporter (Prometheus, Datadog, etc.).

setMetricReporter((name, value) => {
  console.log("metric", name, value);
});

setLogLimits(maxPathLength?: number, maxPayloadLength?: number)

Adjust truncation limits for locations and string payloads.

setLogLimits(160, 8000);

setCleanupHandler(fn: (() => void) | null)

Override cleanup logic (executed on beforeExit, SIGINT, SIGTERM, exit).

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)
info("Service started", "bootstrap");
warning("Slow response", "orders/list", { ms: 1200 });
error(new Error("DB timeout"));
// Express middleware
app.use(errorHandler);

parseRequestError(err)

Normalizes HTTP client errors (axios/fetch/custom) into a safe object.

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)

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");
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    error(err, "/helpers/somefile.js/catch");
  }
};

run();

ESM (no destructuring)

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");
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    errorCapture.error(err, "/helpers/somefile.js/catch");
  }
};

run();

CommonJS (destructuring)

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");
// Usage example
const run = async () => {
  try {
    await someFunction(payload);
  } catch (err) {
    error(err, "/helpers/somefile.js/catch");
  }
};

run();

CommonJS (no destructuring)

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");
// 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

About

Error Handler Helper (Sentry)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors