@nodifier/errvo
v1.0.0
Published
Utils for handling error coming from http requests/responses
Downloads
35
Maintainers
Readme
@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
- Native NodeJS http/https request
- 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);
});