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

express-simple-error-handler

v1.3.1

Published

Biblioteca para tratar erros utilizando express

Downloads

3

Readme

Express Simple Error Handler

This library was created to standardize and simplify exception treatment across Express.js applications. There is no extra configuration required before install it, but Express.js is mandatory.

Goal: simplify and standardize exception treatment and allow a range of responses on error scenarios.

Index


Install

This is a Node.js library and it's available through npm registry.

$ npm install express-simple-error-handler

Use as an object

Errors in your application can be effectively managed through the execute method of an ErrorHandler object. This method requires two parameters: the caught error and an express response object.

When the caught error is "exported from the library", the ErrorHandler will automatically send a default response. This response includes an appropriate "HTTP Status Code" and a message specified in the error object. If the caught error is not exported from the library, then a default "internal error" response will be sent.

import { ErrorHandler, BadRequestError } from 'express-simple-error-handler'

async update(req, res, updateRecord) {
    try {
        if (!req.body) {
            throw new BadRequestError('A record should be sent to update.')
        }

        const updatedRecord = await updateRecord.execute(req.body)
        res.status(200).json({ data: updatedRecord })
    } catch(err) {
        ErrorHandler.execute(err, res)
    }
}

In the provided example, if a body is missing from the request, the ErrorHandler will automatically generate a response with "Status Code 400" along with the following JSON object:

{ "message": "A record should be sent to update." }

On the other hand, if the updateRecord use case throws an unknown error, the ErrorHandler will generate a response with "Status Code 500" along with the following JSON object:

{ "message": "Internal Error." }

Use as a middleware

It's also possible to manage errors in the application through an errorHandlerMiddleware. There are several implementation options, including calling it within a specific route, incorporating it into the routing system (router), or placing it at the application root.

The provided examples below demonstrate the implementation of the errorHandlerMiddleware with the referenced controller:

import { ErrorHandler, BadRequestError } from 'express-simple-error-handler'

export function recordController(updateRecord) {
    return () => ({
        async update(req, res, next) {
            try {
                if (!req.body) {
                    throw new BadRequestError('Deve ser enviado um objeto para atualização.')
                }

                const updatedRecord = await updateRecord.execute(req.body)
                res.status(200).json({ data: updatedRecord })
            } catch(err) {
                next(err)
            }
        }
    })
}

Implementations:

  1. Route:
    import express from 'express'
    import { errorHandlerMiddleware } from 'express-simple-error-handler'
    import { recordController } from './RecordController'
    import { updateRecord } from '../useCase/updateRecord'
    
    const app = express()
    const recordController = recordController(updateRecord)
    
    app.patch('/updateRecord', recordController.update, errorHandlerMiddleware)
    app.listen(3000)
  2. Routing system (router):
    import * as express from 'express'
    import { errorHandlerMiddleware } from 'express-simple-error-handler'
    import { recordController } from './RecordController'
    import { updateRecord } from '../useCase/updateRecord'
    
    
    const router = express.Router()
    const recordController = recordController(updateRecord)
    
    export function recordsRouter() {
        router.patch('/updateRecord', recordController.update)
        router.use(errorHandlerMiddleware)
    }
  3. Application root:
    import express from 'express'
    import { errorHandlerMiddleware } from 'express-simple-error-handler'
    import { recordController } from './RecordController'
    import { updateRecord } from '../useCase/updateRecord'
    
    const app = express()
    const recordController = recordController(updateRecord)
    
    app.patch('/updateRecord', recordController.update)
    app.use(errorHandlerMiddleware)
    
    app.listen(3000)

Available errors

The following errors are available to be thrown. Each error has by default a "HTTP status code" and a built in message. If a custom message is not specified by the user, then the built in message will be sent along with the status code.

BadRequestError

  • Default Message: "Invalid request."
  • Status Code: 400

InvalidPasswordError

  • Default Message: "Invalid password."
  • Status Code: 401

UnauthorizedError

  • Default Message: "Invalid credentials."
  • Status Code: 401

ForbiddenError

  • Default Message: "Access forbidden."
  • Status Code: 403

NotFoundError

  • Default Message: "Resource not found."
  • Status Code: 404

Unknown errors

Any error thrown by the application that is not exported by the library will be considered an "unknown error" and will be handled as an "internal error".

  • Default Message: "Internal error."
  • Status Code: 500

Contribute

Feel free to contribute to the library!

For improvement suggestions or new error additions, follow the step by step guide below:

  1. Push the improvement code to a branch named with the following rule:
    • Error adition: feature/error-addition-user-name
    • Improvements: improvement/user-name
  2. Don't forget to write unit tests to ensure that the implemented feature or improvement is working as expected.
  3. Open a Merge Request following the naming rule below:
    • Error adition: Error: new-error-name(s) - user-name
    • Improvements: Improvement: short-improvement-description - user-name