Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
6f60f8bd94 | |||
07606cd996 |
4
package-lock.json
generated
4
package-lock.json
generated
@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.4.0",
|
||||
"version": "0.10.4",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.4.0",
|
||||
"version": "0.10.4",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ztimson/utils",
|
||||
"version": "0.10.1",
|
||||
"version": "0.10.4",
|
||||
"description": "Utility library",
|
||||
"author": "Zak Timson",
|
||||
"license": "MIT",
|
||||
|
19
src/xhr.ts
19
src/xhr.ts
@ -75,21 +75,16 @@ export class XHR {
|
||||
await new Promise<void>(res => fn(resp, () => res()));
|
||||
}
|
||||
|
||||
if(!resp.ok) throw new Error(resp.statusText);
|
||||
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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
XHR.addInterceptor((resp: Response, next: () => void) => {
|
||||
const getErr = (e: any) => e.error?.message || e.reason?.message || e.message || e.statusText || e.toString();
|
||||
if(resp.status == 200) return next();
|
||||
if(resp.status == 400) throw new BadRequestError(getErr(resp));
|
||||
if(resp.status == 401) throw new UnauthorizedError(getErr(resp));
|
||||
if(resp.status == 403) throw new ForbiddenError(getErr(resp));
|
||||
if(resp.status == 404) throw new NotFoundError(getErr(resp));
|
||||
if(resp.status == 500) throw new InternalServerError(getErr(resp));
|
||||
throw new CustomError(getErr(resp), resp.status);
|
||||
const payload = await decode();
|
||||
if(resp.ok) return payload;
|
||||
const text = resp.statusText || (typeof payload == 'string' ? payload : null);
|
||||
throw (text ? new Error(text) : payload);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user