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 🙏

© 2025 – Pkg Stats / Ryan Hefner

any-restapi-errors

v2.2.5

Published

npm module for handling and logging errors in Node.js API

Downloads

106

Readme

ES6-based library that effortlessly combines error handling and logging for your RESTful APIs.

Why It’s a Must-Have

  • Simple to use: Just throw a new apiError(404) (or include a custom message), then catch and handle it with built-in logging.
  • Automatic Error Logging: Upon catching an error, call error.errorLogger() to create an error.log file containing a comprehensive JSON.
  • Ready made consistent response object generated with error.resObj().It can be use to return response in res.status(error.statusCode || 500).send(error.resObj());
  • ES6-First & Lightweight: With modern syntax and minimal dependency overhead, it integrates seamlessly into Express/Node.js apps.

Ideal For...

  • Express/Node.js developers seeking consistent, easy-to-maintain error handling.
  • Teams striving for better observability—this tool offers immediate insight into what went wrong, complete with diagnostics.
  • Anyone building REST APIs who wants to move fast without sacrificing reliability.

Example

import { apiError } from 'any-restapi-errors';
try {
  if (user === null) {
    /* Handle the case where user is null */
    throw new apiError(404);
    /* or with name as well throw new apiError(404, "User Not Found", true); */
    //params are : new apiError(statusCode,name, isOperational, message, description)
   }
} catch (error) {
  // Log the error using the custom error logger
  error.errorLogger();
  res.status(error.statusCode || 500).send(error.resObj());
  /** or res.status(error.statusCode || 500).send({
    error: {
      name: error.name,
      message: error.message,
      statusCode: error.statusCode,
      description:error.description,
      isOperational: error.isOperational
    }
  }); **/
}

Operational Error (not a bug done by programmers) examples

  • failed to connect to server
  • failed to resolve hostname
  • invalid user input
  • request timeout
  • server returned a 500 response
  • socket hang-up
  • system is out of memory

Operational Error Handler

  • Quick use import {apiError} from 'any-restapi-errors'; throw new apiError(404); : this will throw error object which will have enough detail in error object. You can catch error in catch block. error will have errorLogger method and necessary properties.You can pass any error code ex. 400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,500,501,502,503,504,505,511.
  • Detailed use Throw: throw new apiError(statusCode, "Your message")

Error Logger

  • when you use error.errorLogger(); method it will create error.log file and logs details like statusCode, name, isOperational, message, description,stack,level, timestamp.
  • Following Json object example will be created in error.log file when error will occure.
{
  statusCode: 404,
  name: 'ApiError',
  message: 'Not Found',
  description: 'The requested page could not be found but may be available again in the future',
  isOperational: true,
  stack: 'ApiError: Not Found\n' +
    '    at new BaseError (file:///D:/projects/any-restapi-errors/apiErrors/baseError.js:10:8)\n' + ...',
  level: 'error',
  timestamp: '2025-08-21 14:16:50'
}

Response Object

  • error.resObj() can be use to return response in res.status(error.statusCode || 500).send(error.resObj()); which will return following error object
 {
    "error": {
        "name": "ApiError",
        "message": "Not Found",
        "description": "The requested page could not be found but may be available again in the future",
        "statusCode": 404
    }
}

Programatic Errors (bug introduced by programmers)

  • Programmer errors almost always → 500 (generic).
  • Don’t leak stack traces or sensitive details to the client.
  • Handle them with logging + monitoring, not detailed HTTP codes.

Examples

  • Using an undefined variable
  • Accessing properties of null / undefined
  • Forgetting await → unhandled Promise rejections
  • Infinite loops / recursion → stack overflow
  • Wrong type assumptions (e.g., calling .map on a non-array)
  • These are bugs in code, not client/server operational issues.

Exit gracefully if its not operational errors (Programatic errors)

  • These errors can often cause issues in your apps like memory leaks and high CPU usage. The best thing to do is to crash the app and restart it gracefully by using the Node.js cluster mode or a tool like PM2.
process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  if (!error.isOperational) {
    // log it and exit the process
    process.exit(1);
  }
})

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // log it, exit the process
  process.exit(1);
})