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

@pedromiotti/exerror

v1.0.2

Published

Custom express error handler

Downloads

7

Readme

Exerror Logo

A lightweight library to gracefully handle errors in expressJs

GitHub repo size npm GitHub

import express from 'express';
const app = express();

import { errorHandler }  from '@pedromiotti/exerror'; // Import it

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.use(errorHandler); //Simply pass the errorHandler middleware

app.listen(3000)

Installation

$ npm install @pedromiotti/exerror

Use

// Controller

import express from 'express';
const UserService = require('../services/UserService');

class UserController{
    public static async RegisterUser( req: express.Request, res: express.Response, next: express.NextFunction): Promise<void>{
        try {
            const {username, password} = req.body;
            let user: Promise<String> = await UserService.registerUser(username, password);

            res.status(200).send(user)
        }
        catch (e) {
            next(e); // Catch the error thrown by the `UserService.registerUser` function and pass it to the middleware
        }
    }
}

export { UserController };
// Service 

import { ApplicationError, CommonHTTPExceptions }  from '@pedromiotti/exerror';

import { UserModel } from "../models/UserModel";

const registerUser = async(username: string, password: string): Promise<String> => {
    let user;
    /*
    * Throw a new ApplicationError either with our pre-defined errors or 
    *  you can create your own as shown bellow.
    */
    if(!username || !password) 
        throw new ApplicationError(CommonHTTPExceptions.BAD_REQUEST);   

    try{
        user = await UserModel.registerUser();
    }
    catch (e) {
        /*
        * Trying to register a User on the database. If the database throws an error,
        * it will also be caught by our middleware.
        */
        throw new ApplicationError(e); 
    }

    return user;
}

export { registerUser };

An example of how the first error will look for the client.

{
    "error": {
        "name": "ApplicationError",
        "type": "CLIENT",
        "code": "BAD_REQUEST",
        "message": "Bad request"
    },
    "success": false
}

And the second error, if the database does not exist.

{
  "error": {
    "name": "ApplicationError",
    "code": "ER_BAD_DB_ERROR",
    "message": "ER_BAD_DB_ERROR: Unknown database 'express'"
  },
  "success": false
}

Creating your own custom errors

  1. Create a folder called exceptions (optional, and you can call whatever you want).

  2. Inside create a file. Let's call it customExceptions.ts.

  3. Start by importing our ERROR_TYPES:

    import { ERROR_TYPES } from '@pedromiotti/exerror'; 
  4. Then you can create your error object :

    const CustomExceptions = {};
  5. Each error has to have this template:

     ERROR_NAME: {
         type: ,
         code: "",
         message: "",
         statusCode: ,
     }

    For example:

     MISSING_INFORMATION: {
         type: ERROR_TYPES.CLIENT,
         code: "MISSING_INFORMATION",
         message: "Fill all the information required.",
         statusCode: 400,
     }

OBS: You have to use one of our ERROR_TYPES for the type field, they are:

 enum ERROR_TYPES {
     INTERNAL = "INTERNAL",
     CLIENT = "CLIENT",
     NETWORK = "NETWORK",
     SERVER = "SERVER",
     UNKNOWN = "UNKNOWN"
 }

Using your custom errors

import { ApplicationError }  from '@pedromiotti/exerror';
import { UserModel } from "../models/UserModel";
import { CustomExceptions } from "../exceptions/customExceptions"; // Import it

const registerUser = async(username: string, password: string): Promise<String> => {
    let user;
    
    if(!username || !password) throw new ApplicationError(CustomExceptions.MISSING_INFORMATION); // And simply use it

    try{
        user = await UserModel.registerUser();
    }
    catch (e) {
        throw new ApplicationError(e);
    }

    return user;
}

export { registerUser };

There is and example project inside the demo folder.

Licence

MIT