From 3ca956e531bf81039b1ac4e156cf502489842a9e Mon Sep 17 00:00:00 2001 From: ztimson Date: Fri, 31 May 2024 10:04:51 -0400 Subject: [PATCH] Fixed fetch errors --- package.json | 2 +- src/errors.ts | 12 ------------ src/xhr.ts | 19 +++++++++++++++++++ 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index 2014d58..01e6a8f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.10.0", + "version": "0.10.1", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/errors.ts b/src/errors.ts index e99b8bd..1f7437e 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,15 +1,3 @@ -import {XHR} from './xhr'; - -XHR.addInterceptor((resp: Response, next: () => void) => { - if(resp.status == 200) return next(); - if(resp.status == 400) throw new BadRequestError(resp.statusText); - if(resp.status == 401) throw new UnauthorizedError(resp.statusText); - if(resp.status == 403) throw new ForbiddenError(resp.statusText); - if(resp.status == 404) throw new NotFoundError(resp.statusText); - if(resp.status == 500) throw new InternalServerError(resp.statusText); - throw new CustomError(resp.statusText, resp.status); -}); - export class CustomError extends Error { static code = 500; diff --git a/src/xhr.ts b/src/xhr.ts index 68104fd..43489fc 100644 --- a/src/xhr.ts +++ b/src/xhr.ts @@ -1,3 +1,11 @@ +import { + BadRequestError, + CustomError, + ForbiddenError, + InternalServerError, + NotFoundError, + UnauthorizedError +} from './errors.ts'; import {clean} from './objects'; export type Interceptor = (request: Response, next: () => void) => void; @@ -74,3 +82,14 @@ export class XHR { }); } } + +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); +});