2023-07-11 19:28:27 +03:00

40 lines
1.1 KiB
TypeScript

import { captureException, withScope } from '@sentry/nextjs';
import type { AxiosError } from 'axios';
import { isAxiosError } from 'axios';
import { pick } from 'radash';
function getErrorMessage<T extends { error?: string; errors?: string[]; message?: string }>(
error: AxiosError<T>
) {
return (
error.response?.data?.error ||
error.response?.data?.errors?.[0] ||
error.response?.data?.message ||
error.message
);
}
export async function withHandleError<T>(fn: Promise<T>) {
return fn.catch((error_: AxiosError | Error) => {
if (isAxiosError(error_)) {
const err = pick(error_, ['code', 'message', 'status', 'cause']);
const data = error_.config?.data;
const params = error_.config?.params;
const opts = { ...err, data, params };
const message = getErrorMessage(error_);
withScope((scope) => {
(Object.keys(opts) as Array<keyof typeof opts>).forEach((key) => {
scope.setExtra(key, JSON.stringify(opts[key]));
});
captureException(error_);
});
throw new Error(message);
}
return null as unknown as T;
});
}