Created
November 29, 2021 16:36
-
-
Save RohitRox/4780c8a0bb99026b14846841776cd80e to your computer and use it in GitHub Desktop.
Axios Error Decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AxiosError } from "axios"; | |
/** | |
* Decorator for service instance methods that does ajax calls | |
* @param {string} message - ajax operation name | |
* @param {any=} defaultData - optional default data to return if ajax call fails | |
*/ | |
export function axiosError(message: string, defaultData?: any) { | |
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { | |
const originalMethod = descriptor.value; | |
descriptor.value = async function (...args: any[]) { | |
try { | |
await originalMethod.apply(this, args); | |
} catch (err) { | |
const e = err as AxiosError | |
if (defaultData) { | |
console.error(`${message} - failed: ${e.message}`) | |
return defaultData | |
} | |
if (e.code === "ECONNREFUSED") { | |
throw new ExternalHTTPError(`${message} - failed: Host unreachable: ${e.message}`) | |
} | |
if (e.response) { | |
throw new ExternalHTTPError(`${message} - failed with some response: ${e.message}`, { | |
responseStatus: e.response.status, | |
responseText: e.response.statusText, | |
responseData: e.response.data | |
}) | |
} | |
throw new ExternalHTTPError(`${message} - failed without response: ${e.message}`) | |
} | |
} | |
return descriptor; | |
}; | |
} | |
export default class BaseError extends Error{ | |
status: number | |
message: string | |
additional?: object | |
constructor(general: string, message?: string, additional?: object) { | |
super(general) | |
let msg = general | |
if (message) msg = `${msg}: ${message}` | |
this.message = msg | |
this.additional = additional | |
} | |
toJson() { | |
return { | |
message: this.message, | |
...this.additional | |
} | |
} | |
} | |
export class ExternalHTTPError extends BaseError { | |
static MESSAGE = "Incomplete server response" | |
status= 200 | |
constructor(message?: string, additional?: object) { | |
super(ExternalHTTPError.MESSAGE, message, additional) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment