Utils for handling error coming from http requests/responses
You can import the module to your code as follows:
import { HttpError } from "@nodify/errvo";
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.
- BadRequestError
- UnauthorizedError
- ForbiddenError
- NotFoundError
- InternalServerError
- BadGatewayError
- TimeoutError
- OtherError
- Native NodeJS http/https request
- Axios request module
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();
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);
});