38 lines
1.1 KiB
TypeScript
38 lines
1.1 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';
|
|
|
|
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 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;
|
|
});
|
|
}
|