@nodifier/errvo
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@nodifier/errvo

Utils for handling error coming from http requests/responses

How to use?

You can import the module to your code as follows:

import { HttpError } from "@nodify/errvo";

Throwing http request error

throw new HttpError(error);

Expected output from the thrown object would be the same as the standard Error object with some preconfigured value tailored to http request errors.

It will also logs the error with the error log level.

List of http errors supported

  • BadRequestError
  • UnauthorizedError
  • ForbiddenError
  • NotFoundError
  • InternalServerError
  • BadGatewayError
  • TimeoutError
  • OtherError

Supports

  1. Native NodeJS http/https request
  2. Axios request module

Full examples

NodeJS native http/https

import http from 'http';
import { HttpError } from '@nodifier/errvo';

const options: http.RequestOptions = {
hostname: 'api.example.com',
port: 443,
path: '/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token' // Replace with your actual token
}
};

const postData = JSON.stringify({
name: 'John Doe',
email: '[email address removed]'
});

const req = http.request(options, (res) => {
    res.on('error', (error) => {
        /**
         * Throwing a http response error and logging it
         * 
        */
        throw new HttpError(error);
    });
}

/**
 * Throwing a http request error and logging it
 * 
*/
req.on('error', (error) => {
 throw new HttpError(error);
});

req.write(postData);
req.end();

Axios

import axios from 'axios';
import { HttpError } from '@nodifier/errvo';

const options = {
    method: 'post',
    url: 'https://api.example.com/users',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your_token' // Replace with your actual token
    },
    data: {
        name: 'John Doe',
        email: '[email address removed]'
    }
};

axios
    .request(options)
    .then((response) => {
        if(response.status && response.status >= 400) {
            throw new HttpError(response);
        }
    })
    .catch((error) => {
        throw new HttpError(error);
    });

Package Sidebar

Install

npm i @nodifier/errvo

Weekly Downloads

0

Version

1.0.0

License

ISC

Unpacked Size

10.2 kB

Total Files

7

Last publish

Collaborators

  • gamemasterdev