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

ops-error

v1.2.1

Published

Error handling made in simple for express, koa, fastify and other nodejs framework

Downloads

8

Readme

OpsError

npm version License download-url

Error handling made in simple for your favorite nodejs framework.

Features

  • Easy to use.
  • Easy configuration.
  • Custom throw error.
  • Debugging and logging.
  • Support Commonjs, ES6+ and Typescript.
  • Also support Native Nodejs, Express, Koa, Fastify, Hapi and more.

Installation

$ npm install ops-error
//or
$ yarn add ops-error

Usage (example for native nodejs http server)

Of course, OpsError support for other framework you can find code in example folder or this wiki.


const http = require("http");
const ops = require('ops-error');
// or esm and typescript
// import ops from 'ops-error';

// it's using wrap asynchronous.
const app = http.createServer(ops.wrap((req, res) => {
    if (req.url === '/bad') {
        throw new ops.BadRequestError('Bad request error for url /bad');
    }
    if (req.url === '/not') {
        throw new ops.NotFoundError('Not found error for url /not');
    }
    res.end('horayyy');
}));

// if using try and catch block.
const app = http.createServer((req, res) => {
    try {
        if (req.url === '/bad') {
            throw new ops.BadRequestError('Bad request error for url /bad');
        }
        if (req.url === '/not') {
            throw new ops.NotFoundError('Not found error for url /not');
        }
        res.end('horayyy');
    }catch(err) {
        return ops.next(err, req, res);
    }
});

// simple config
ops.config({
    useErrorResponse: (err, req, res) => {
        const data = ops.getError(err, req);
        res.writeHead(data.statusCode, { 'Content-Type': 'application/json;charset=utf-8' });
        res.end(JSON.stringify(data));
    }
});

app.listen(3000, () => {
    console.log('Success running ' + 3000);
});

// example response error if access url /bad :
// {
//     "statusCode": 400,
//     "name": "BadRequestError",
//     "message": "Bad request error for url /bad"
// }

Wiki for framework

  1. Express error handling with ops-error
  2. Koa error handling with ops-error
  3. Fastify error handling with ops-error
  4. Hapi error handling with ops-error
  5. Restify error handling with ops-error

Debugging And Logging

...

ops.config({
    useDebug: true,
    useLogging: (log) => {
        // saveLogErrorAsString(JSON.stringify(log)) 
    },
    // or
    // useLogging: true
    useErrorResponse: (err, req, res) => {
        const data = ops.getError(err, req);
        res.writeHead(data.statusCode, { 'Content-Type': 'application/json;charset=utf-8' });
        res.end(JSON.stringify(data));
    }
});

// example response error if debug = true :
// {
//     "statusCode": 404,
//     "name": "NotFoundError",
//     "message": "User Not Found",
//     "debug": {
//         "stack": [
//             "at Z:\\nodejs\\ops-error\\example\\express\\index.js:23:19"
//         ],
//         "request": {
//             "method": "GET",
//             "uri": "/user",
//             "headers": {
//                 "user-agent": "PostmanRuntime/7.26.5",
//                 "accept": "*/*",
//                 "postman-token": "7e6ee0e1-c692-40db-b71b-7284c80e22bb",
//                 "host": "localhost:3000",
//                 "accept-encoding": "gzip, deflate, br",
//                 "connection": "keep-alive"
//             }
//         },
//         "httpCode": 404
//     }
// }

Custom throw error


// PaymentRequiredError.js

const { OpsError } = require("ops-error");

class PaymentRequiredError extends OpsError {
    getCode() { return 402 };
    getName() { return 'PaymentRequiredError' };
}

module.exports = PaymentRequiredError;

const http = require("http");
const { config, getError, wrap } = require('ops-error');
const PaymentRequiredError = require('./PaymentRequiredError');

const app = http.createServer(wrap((req, res) => {
    if (req.url !== '/pay') {
        throw new PaymentRequiredError('Payment is required. please goto /pay');
    }
    res.end('horayyy');
}));

config({
    useDebug: true,
    useLogging: true,
    useErrorResponse: (err, req, res) => {
        const data = getError(err, req);
        res.writeHead(data.statusCode, { 'Content-Type': 'application/json;charset=utf-8' });
        res.end(JSON.stringify(data));
    }
});

app.listen(3000, () => {
    console.log('Success running ' + 3000);
});

Example Config


...

const ops = require('ops-error');

ops.config({
    useDebug: true,
    useLogging: (log) => {
        // ops.print(log);
        // saveLogErrorAsString(JSON.stringify(log));
    },
    // rename response key. the default is { statusCode, name, message }.
    useRenameResponse: {
        // rename statusCode to code
        statusCode: 'code',
        // rename name to error
        name: 'error'
    },
    useErrorResponse: (err, req, res) => {
        const data = ops.getError(err, req);
        // after useRenameResponse is configured. response was change.
        // console.log(data)
        // {
        //     "code": 400,
        //     "error": "BadRequestError",
        //     "message": "Bad request error for url /bad"
        // }
        res.writeHead(data.code, { 'Content-Type': 'application/json;charset=utf-8' });
        res.end(JSON.stringify(data));
    }
});

...

List Error Available In This Library

|Class |Code | |--- |--- | |BadRequestError|400| |UnauthorizedError|401| |ForbiddenError|403| |NotFoundError|404| |MethodNotAllowedError|405| |RequestTimeoutError|408| |ConflictError|409| |UnsupportedMediaTypeError|415| |UnprocessableEntityError|422| |InternalServerError|500| |NotImplementedError|501| |BadGatewayError|502| |ServiceUnavailableError|503|

Method

|Name |Description | |--- |--- | |ops.config|Configure ops error. Example => ops.config({ yourconfig })| |ops.getError|Display error status, name and message. Example => const data = ops.getError(err, req?);| |ops.print|print in terminal. Example => ops.print(data)| |ops.wrap|Wrap an asynchronous without try and catch. Example => ops.wrap((req, res) => res;)| |ops.next|Optional if an function using try and catch block. Example => ops.next(err, req, res)|

Contact me : [email protected]

License

MIT