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

@emtiaj/custom-errors

v1.0.6

Published

A lightweight custom error handler for Node.js applications, enabling easy creation and management of generic and specific error types with customizable messages and status codes.

Downloads

9

Readme

Custom Errors

A lightweight npm package for custom error handling in Node.js applications. This package allows you to create and manage specific HTTP error types easily, making your error handling more organized and consistent.

Installation

To install the package, run the following command:

npm install @emtiaj/custom-errors

Usage

Importing Custom Errors You can import the custom error classes in your application like this:

import { BadRequestError, UnauthorizedError, NotFoundError } from '@emtiaj/custom-errors';

Creating a Controller Example

Here's how to use the custom errors in your controller methods:

import { BadRequestError, UnauthorizedError, NotFoundError } from '@emtiaj/custom-errors';

const userController = {
  async getUser(req, res, next) {
    try {
      const { userId } = req.params;

      if (!userId) {
        throw new BadRequestError('User ID is required.');
      }

      const user = await fetchUserById(userId); // Replace with your actual data retrieval logic

      if (!user) {
        throw new NotFoundError('User not found.');
      }

      res.status(200).json(user);
    } catch (error) {
      next(error);
    }
  },

  async authenticateUser(req, res, next) {
    try {
      const { username, password } = req.body;

      const isAuthenticated = await authenticate(username, password); // Replace with your authentication logic
      if (!isAuthenticated) {
        throw new UnauthorizedError('Invalid username or password.');
      }

      res.status(200).json({ message: 'Authenticated successfully!' });
    } catch (error) {
      next(error);
    }
  }
};

Error Handling Middleware

Make sure to set up an error handling middleware to catch and respond to these errors:

const errorHandler = (err, req, res, next) => {
  const statusCode = err.statusCode || 500;
  const message = err.message || 'An unexpected error occurred.';

  res.status(statusCode).json({
    status: 'error',
    statusCode,
    message
  });
};

Use the error handler in your Express app.js/server.js

app.use(errorHandler);

Using Default Error Handling Middleware

To use the error handler in your Express application, import it and use it as middleware:

import { errorHandler } from '@emtiaj/custom-errors';

// After your routes
app.use(errorHandler);

Available Error Types

  • BadRequestError: Indicates that the server cannot process the request due to a client error (400).
  • UnauthorizedError: Indicates that authentication is required and has failed (401).
  • ForbiddenError: Indicates that the server understands the request but refuses to authorize it (403).
  • NotFoundError: Indicates that the requested resource could not be found (404).
  • MethodNotAllowedError: Indicates that the method specified in the request is not allowed (405).
  • ConflictError: Indicates a conflict with the current state of the resource (409).
  • InternalServerError: Indicates an unexpected condition was encountered (500).
  • ServiceUnavailableError: Indicates that the server is currently unable to handle the request due to temporary overload or maintenance (503).

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue.

Author

Imtiaz Ahmed