|
| 1 | +import {useToast} from '@sanity/ui' |
| 2 | +import {pick} from 'lodash' |
| 3 | +import {useCallback} from 'react' |
| 4 | +import {catchError, EMPTY, map, of, type OperatorFunction, tap} from 'rxjs' |
| 5 | + |
| 6 | +import {isRecord} from '../../util' |
| 7 | +import {strings} from './strings' |
| 8 | +import {type ErrorWithId} from './types' |
| 9 | + |
| 10 | +const TOAST_ID = 'copyErrorDetails' |
| 11 | + |
| 12 | +/** |
| 13 | + * @internal |
| 14 | + */ |
| 15 | +export function useCopyErrorDetails(error: unknown, eventId?: string | null): () => void { |
| 16 | + const toast = useToast() |
| 17 | + |
| 18 | + return useCallback(() => { |
| 19 | + of<ErrorWithId>({error, eventId}) |
| 20 | + .pipe( |
| 21 | + serializeError(), |
| 22 | + catchError((serializeErrorError) => { |
| 23 | + console.error(serializeErrorError) |
| 24 | + toast.push({ |
| 25 | + status: 'error', |
| 26 | + title: strings['copy-error-details.toast.get-failed'], |
| 27 | + id: TOAST_ID, |
| 28 | + }) |
| 29 | + return EMPTY |
| 30 | + }), |
| 31 | + tap((errorDetailsString) => { |
| 32 | + navigator.clipboard.writeText(errorDetailsString) |
| 33 | + toast.push({ |
| 34 | + status: 'success', |
| 35 | + title: strings['copy-error-details.toast.succeeded'], |
| 36 | + id: TOAST_ID, |
| 37 | + }) |
| 38 | + }), |
| 39 | + catchError((copyErrorError) => { |
| 40 | + console.error(copyErrorError) |
| 41 | + toast.push({ |
| 42 | + status: 'error', |
| 43 | + title: strings['copy-error-details.toast.copy-failed'], |
| 44 | + id: TOAST_ID, |
| 45 | + }) |
| 46 | + return EMPTY |
| 47 | + }), |
| 48 | + ) |
| 49 | + .subscribe() |
| 50 | + }, [error, eventId, toast]) |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * @internal |
| 55 | + */ |
| 56 | +export function serializeError(): OperatorFunction<ErrorWithId, string> { |
| 57 | + return map<ErrorWithId, string>(({error, eventId}) => { |
| 58 | + // Extract the non-enumerable properties of the provided `error` object. This is particularly |
| 59 | + // useful if the provided `error` value is an instance of `Error`, whose properties are |
| 60 | + // non-enumerable. |
| 61 | + const errorInfo = isRecord(error) ? pick(error, Object.getOwnPropertyNames(error)) : undefined |
| 62 | + return JSON.stringify({error: errorInfo, eventId}, null, 2) |
| 63 | + }) |
| 64 | +} |
0 commit comments