2024-09-18 14:02:05 +03:00

46 lines
1.3 KiB
TypeScript

import { HttpError } from './error';
import { captureException, getCurrentScope } from '@sentry/nextjs';
import type { AxiosError } from 'axios';
import { isAxiosError } from 'axios';
import { pick } from 'radash';
type ResponseError = {
Error?: string;
error?: string;
errors?: string[];
fullMessage?: string;
message?: string;
};
function getErrorMessage<T extends ResponseError>(error: AxiosError<T>) {
return (
error.response?.data?.Error ||
error.response?.data?.error ||
error.response?.data?.errors?.[0] ||
error.response?.data.fullMessage ||
error.response?.data?.message ||
error.message
);
}
export async function withHandleError<T>(fn: Promise<T>) {
return fn.catch((error_: AxiosError | Error) => {
if (isAxiosError(error_)) {
const message = getErrorMessage(error_);
if (error_.config && error_.response?.status && error_.response?.status >= 500) {
const scope = getCurrentScope();
const extras = pick(error_.config, ['url', 'data', 'params']);
scope.setExtras(extras);
scope.setTag('target_url', extras.url);
error_.message += ` | ${message}`;
captureException(error_);
}
throw new HttpError(message, error_.status || error_.response?.status);
}
return null as unknown as T;
});
}