Changed XHR error handling
All checks were successful
Build / Build NPM Project (push) Successful in 1m13s
Build / Tag Version (push) Successful in 16s
Build / Publish (push) Successful in 22s

This commit is contained in:
Zakary Timson 2024-05-31 13:42:28 -04:00
parent 07606cd996
commit 6f60f8bd94
3 changed files with 13 additions and 7 deletions

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@ztimson/utils",
"version": "0.10.2",
"version": "0.10.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ztimson/utils",
"version": "0.10.2",
"version": "0.10.4",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.12",

View File

@ -1,6 +1,6 @@
{
"name": "@ztimson/utils",
"version": "0.10.3",
"version": "0.10.4",
"description": "Utility library",
"author": "Zak Timson",
"license": "MIT",

View File

@ -75,10 +75,16 @@ export class XHR {
await new Promise<void>(res => fn(resp, () => res()));
}
if(!resp.ok) throw new Error(resp.statusText);
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json();
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
return resp;
const decode = async () => {
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json();
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
return resp;
}
const payload = await decode();
if(resp.ok) return payload;
const text = resp.statusText || (typeof payload == 'string' ? payload : null);
throw (text ? new Error(text) : payload);
});
}
}