1.2.1 • Published 4 years ago

ops-error v1.2.1

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

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

ClassCode
BadRequestError400
UnauthorizedError401
ForbiddenError403
NotFoundError404
MethodNotAllowedError405
RequestTimeoutError408
ConflictError409
UnsupportedMediaTypeError415
UnprocessableEntityError422
InternalServerError500
NotImplementedError501
BadGatewayError502
ServiceUnavailableError503

Method

NameDescription
ops.configConfigure ops error. Example => ops.config({ yourconfig })
ops.getErrorDisplay error status, name and message. Example => const data = ops.getError(err, req?);
ops.printprint in terminal. Example => ops.print(data)
ops.wrapWrap an asynchronous without try and catch. Example => ops.wrap((req, res) => res;)
ops.nextOptional if an function using try and catch block. Example => ops.next(err, req, res)

Contact me : herudi7@gmail.com

License

MIT

1.2.1

4 years ago

1.2.0

4 years ago

1.1.9

4 years ago

1.1.8

4 years ago

1.1.7

4 years ago

1.1.6

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.1

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.0

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago