Skip to content

Commit

Permalink
Allow wrapApiError to support non-Errors (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
ted-faros authored May 9, 2023
1 parent a4ec178 commit eb7a734
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,14 @@ function isAxiosError(error: Error): error is AxiosError {
return (error as any).isAxiosError;
}

function isError(error: any): error is Error {
return 'name' in error && 'message' in error;
}

/** Strips verbose properties that libraries like Axios attach to errors */
export function wrapApiError(error: Error, message?: string): Error {
export function wrapApiError(maybeError: Error, message?: string): Error {
let error = isError(maybeError) ?
maybeError : Error(JSON.stringify(maybeError));
if (!isAxiosError(error)) {
const cause = VError.cause(error);
if (cause) {
Expand Down
7 changes: 7 additions & 0 deletions test/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ describe('errors', () => {
);
});

test('wraps the non-error without drama', () => {
const cause: any = {name: 'not-an-error'};
expect(sut.wrapApiError(cause, 'message')).toEqual(
new WError(Error(JSON.stringify(cause)), 'message')
);
});

test('includes info field for axios error', () => {
const error = createAxiosError('message1');
const wrappedError: any = sut.wrapApiError(error, 'message');
Expand Down

0 comments on commit eb7a734

Please sign in to comment.