44 lines
1.2 KiB
TypeScript
44 lines
1.2 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 message = getErrorMessage(error_);
|
|
const opts = { ...err, data, message, params };
|
|
|
|
error_.message += ` | ${message}`;
|
|
|
|
withScope((scope) => {
|
|
(Object.keys(opts) as Array<keyof typeof opts>).forEach((key) => {
|
|
let extra = opts[key];
|
|
if (key === 'data') extra = JSON.stringify(extra);
|
|
scope.setExtra(key, extra);
|
|
});
|
|
captureException(error_);
|
|
});
|
|
|
|
throw new Error(message);
|
|
}
|
|
|
|
return null as unknown as T;
|
|
});
|
|
}
|