npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

is-error-service

v1.2.1

Published

A centralized error handling package for Node.js applications

Downloads

12

Readme

Error Service

A centralized error handling package for Node.js applications, providing custom error classes, error handling middleware, and logging with winston. This package simplifies error management in production and development environments.

Installation

Install the package using npm:

npm install is-error-service

Features

  • Custom Error Classes: Predefined error classes for various HTTP errors like AuthError, BadRequestError, NotFoundError, etc.
  • Constants: Provides ERROR for consistent error messaging.
  • Winston Logger: Logging setup for both production and development environments.
  • Error Handling Middleware: Centralized middleware to handle and respond to errors, tailored to the environment.

Setup

  1. app.js
import { errorServiceInit } from 'is-error-service';
import { ENV } from 'is-env-service';

errorServiceInit(process.env.NODE_ENV ?? ENV.DEV.NAME);

Usage

  1. Using Error Classes

The package provides predefined error classes that extend a base CustomError class. You can throw these errors in your application as needed.

Available Error Classes

  • AuthError: 401 Throws an unauthorized access error.
  • BadRequestError: 400 Throws a bad request error.
  • ForbiddenError: Throws a 403 forbidden error.
  • NotFoundError: Throws a 404 not found error.
  • ValidationError: Throws a validation error.
  • InternalServerError: Throws an internalServerError error
import {
  AuthError,
  BadRequestError,
  NotFoundError,
  ValidationError,
  CustomError,
  ForbiddenError,
  InternalServerError,
} from 'is-error-service';

app.get('/auth-required-route', (req, res, next) => {
  // Code: 401
  // Status: fail
  // Message: Unauthorized access. Token is invalid or expired.
  throw new AuthError();
});

app.get('/some-route1', (req, res, next) => {
  // Code: 400
  // Status: fail
  // Message: Bad Request
  throw new BadRequestError();
});

app.get('/some-route2', (req, res, next) => {
  // Code: 500
  // Status: error
  // Message: Something went wrong
  throw new CustomError({
    status: 'error',
    code: 500,
    message: 'Something went wrong',
  });
});

app.get('/some-route3', (req, res, next) => {
  // Code: 403
  // Status: fail
  // Message: Forbidden Access
  throw new ForbiddenError();
});

app.get('/some-route4', (req, res, next) => {
  // Code: 404
  // Status: fail
  // Message: {resource} is not defined
  throw new NotFoundError({ resource: 'user' });
});

app.get('/some-route5', (req, res, next) => {
  // Code: 400
  // Status: fail
  // Message: username must not be empty.
  throw new ValidationError({ message: 'username must not be empty.' });
  // Code: 400
  // Status: fail
  // Message: Invalid Request Data
  throw new ValidationError({});
});

app.get('/some-route6', (req, res, next) => {
  // Code: 500
  // Status: error
  // Message: Fail to modify user.
  throw new InternalServerError({ message: 'Fail to modify user' });
  // Code: 500
  // Status: error
  // Message: Internal Server Error
  throw new InternalServerError({});
});
  1. Error Handling Middleware

The error handling middleware provides different responses based on the current environment. In development, detailed error messages are shown, while in production, more generic messages are returned.

import { errorHandling } from 'is-error-service';

// Use the middleware in your Express application
app.use(errorHandling);
  1. Logger Setup (Winston)

The package includes logging functionality using winston for both development and production environments. Errors and important logs are captured automatically.

import { logger } from 'is-error-service';

// Use logger for custom logging
logger.info('This is an info log');
logger.error('This is an error log');
  1. Error Constants

The package also provides constants for managing consistent error messages.

Example of ERROR and ENV Constants:

import { ERROR } from 'is-error-service';

console.log(ERROR.DEVELOPMENT.NOT_FOUND); // Logs 'Resource not found'
  1. Full Example of Setup

Here’s a complete example of how to use the error service package in an Express app:

import express from 'express';
import {
  errorHandling,
  AuthError,
  logger,
  errorServiceInit,
} from 'is-error_service';

// Initialize the app
const app = express();

errorServiceInit(process.env.NODE_ENV ?? ENV.DEV.NAME);

// Routes
app.get('/auth', (req, res, next) => {
  throw new AuthError(); // Custom error thrown here
});

// Use the error handling middleware
app.use(errorHandling);

// Start the server
app.listen(3000, () => {
  logger.info('Server running on port 3000');
});