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(error: AxiosError) { 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(fn: Promise) { 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; }); }