[Polyfill > Request] Add error handling

This commit is contained in:
Ducko 2021-12-23 17:17:55 +00:00
parent 6689c99589
commit 930fc951dd
1 changed files with 38 additions and 21 deletions

View File

@ -5,7 +5,10 @@ const querystring = require("querystring");
const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => { const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fullUrl = `${url}${qs != null ? `?${querystring.stringify(qs)}` : ''}`; // With query string const fullUrl = `${url}${qs != null ? `?${querystring.stringify(qs)}` : ''}`; // With query string
const req = https.request(fullUrl, {
let req;
try {
req = https.request(fullUrl, {
method, method,
headers, headers,
timeout timeout
@ -24,6 +27,11 @@ const nodeReq = ({ method, url, headers, qs, timeout, body, stream }) => {
resolve(res); resolve(res);
}); });
} catch (e) {
return resolve(e);
}
req.on('error', resolve);
if (body) req.write(body); // Write POST body if included if (body) req.write(body); // Write POST body if included
@ -40,10 +48,19 @@ const request = (options, callback) => { // Main function
// log('Polyfill > Request', options.method, options.url); // log('Polyfill > Request', options.method, options.url);
const listener = {}; const listeners = {};
nodeReq(options).then(async (res) => { // No error handling because yes nodeReq(options).then(async (res) => { // No error handling because yes
if (listener['response']) listener['response'](res); const isError = !res.agent;
if (isError) {
if (listeners['error']) listeners['error'](res);
if (callback) callback(res, null, null); // Return null for others?
return;
}
if (listeners['response']) listeners['response'](res);
if (!callback) return; if (!callback) return;
let body = ''; let body = '';
@ -58,7 +75,7 @@ const request = (options, callback) => { // Main function
return { return {
on: (type, handler) => { on: (type, handler) => {
listener[type] = handler; listeners[type] = handler;
} }
} }
}; };