From 4561e06b61f95bfccef14db0d17896a1dff14979 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Thu, 21 Mar 2024 10:47:14 -0400 Subject: [PATCH] refactor: throw a custom S5Error --- src/axios.ts | 52 ++++++++++++++++++++++++++++----------------------- src/client.ts | 10 ++++++++++ 2 files changed, 39 insertions(+), 23 deletions(-) diff --git a/src/axios.ts b/src/axios.ts index 14defd5..5eed910 100644 --- a/src/axios.ts +++ b/src/axios.ts @@ -1,31 +1,37 @@ -import Axios, { AxiosRequestConfig } from "axios"; +import Axios, {AxiosError, AxiosRequestConfig} from "axios"; +import {S5Error} from "#client.js"; export const customInstance = ( - config: AxiosRequestConfig, - options?: AxiosRequestConfig, + config: AxiosRequestConfig, + options?: AxiosRequestConfig, ): Promise => { - const source = Axios.CancelToken.source(); + const source = Axios.CancelToken.source(); - /* - Hack to ensure that the data is passed to the request as an option. - */ - if (options?.data) { - config = config || {}; - config.data = options.data; - delete config.data; - } + /* + Hack to ensure that the data is passed to the request as an option. + */ + if (options?.data) { + config = config || {}; + config.data = options.data; + delete config.data; + } - const instance = Axios.create({ baseURL: options?.baseURL }); - const promise = instance({ - ...config, - ...options, - cancelToken: source.token, - }).then(({ data }) => data); + const instance = Axios.create({baseURL: options?.baseURL}); + const promise = instance({ + ...config, + ...options, + cancelToken: source.token, + }).then(({data}) => data).catch((error) => { + if (Axios.isCancel(error)) { + return; + } + throw new S5Error((error as AxiosError).message, (error as AxiosError).response?.status as number); + }) - // @ts-ignore - promise.cancel = () => { - source.cancel("Query was cancelled"); - }; + // @ts-ignore + promise.cancel = () => { + source.cancel("Query was cancelled"); + }; - return promise; + return promise; }; diff --git a/src/client.ts b/src/client.ts index b00e6de..3ea2f25 100644 --- a/src/client.ts +++ b/src/client.ts @@ -70,6 +70,16 @@ import { Multihash } from "@lumeweb/libs5/lib/multihash.js"; import { blake3 } from "@noble/hashes/blake3"; import { base64urlDecode, base64urlEncode } from "#utils/encoding.js"; +export class S5Error extends Error { + public statusCode: number; + + constructor(message: string, statusCode: number) { + super(message); + this.name = "S5Error"; + this.statusCode = statusCode; + } +} + /** * The S5 Client which can be used to access S5-net. */