Skip to content

Commit

Permalink
fix: Improve error type detection (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
svsool committed Mar 13, 2021
1 parent 9974edb commit e955d9b
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/axiosBetterStacktrace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ declare module 'axios' {
}
}

// toString used instead of instanceOf for detecting error type to prevent problem mentioned in issue #5
const isError = (error: unknown): error is Error =>
Object.prototype.toString.call(error) === '[object Error]';

const isAxiosError = (error: unknown): error is AxiosError =>
error instanceof Error && (error as AxiosError).isAxiosError;
isError(error) && (error as AxiosError).isAxiosError;

const axiosMethods = [
'request',
Expand Down Expand Up @@ -57,21 +61,19 @@ const axiosBetterStacktrace = (axiosInstance?: AxiosInstance, opts: { errorMsg?:
// enhance original response error with a topmostError stack trace
const responseErrorInterceptorId = axiosInstance.interceptors.response.use(
(response) => {
if (response.config && response.config.topmostError instanceof Error) {
if (response.config && isError(response.config.topmostError)) {
// remove topmostError to not clutter config and expose it to other interceptors down the chain
delete response.config.topmostError;
}

return response;
},
(error: unknown) => {
if (isAxiosError(error) && error.config && error.config.topmostError instanceof Error) {
if (isAxiosError(error) && error.config && isError(error.config.topmostError)) {
error.originalStack = error.stack;
error.stack = `${error.stack}\n${error.config.topmostError.stack}`;

delete error.config.topmostError;

throw error;
}

throw error;
Expand Down

0 comments on commit e955d9b

Please sign in to comment.