import { captureException, withScope } from '@sentry/nextjs'; import type { AxiosError } from 'axios'; import { isAxiosError } from 'axios'; import { pick } from 'radash'; function getErrorMessage( error: AxiosError ) { return ( error.response?.data?.error || error.response?.data?.errors?.[0] || error.response?.data?.message || error.message ); } export async function withHandleError(fn: Promise) { 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).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; }); }