| @@ -1,11 +1,19 @@ | ||
| 1 | 1 | import { __ } from '@wordpress/i18n' |
| 2 | -import { isAxiosError } from 'axios' | |
| 2 | +import { isAxiosError, isCancel } from 'axios' | |
| 3 | 3 | |
| 4 | 4 | export const handleUnknownError = (error: unknown) => { |
| 5 | 5 | console.error(error) |
| 6 | 6 | } |
| 7 | 7 | |
| 8 | +/** | |
| 9 | + * Whether a rejection came from the caller aborting the request rather than | |
| 10 | + * from a failure — axios rejects cancelled requests with no response attached, | |
| 11 | + * so these must not be surfaced to the user as errors. | |
| 12 | + */ | |
| 13 | +export const isAbortError = (error: unknown): boolean => | |
| 14 | + isCancel(error) || error instanceof DOMException && 'AbortError' === error.name | |
| 15 | + | |
| 8 | 16 | export const unpackErrorResponse = (error: unknown): string => { |
| 9 | 17 | if (isAxiosError(error)) { |
| 10 | 18 | if (error.response) { |
| 11 | 19 | const responseData: unknown = error.response.data |
| @@ -21,8 +29,18 @@ | ||
| 21 | 29 | return __('An unknown error occurred.', 'code-snippets') |
| 22 | 30 | } |
| 23 | 31 | |
| 24 | 32 | /** |
| 33 | + * Whether a request finished without the browser receiving a response. | |
| 34 | + * | |
| 35 | + * Nothing can be concluded about the write itself from this: the request may | |
| 36 | + * never have arrived, or it may have been handled and the response lost on the | |
| 37 | + * way back. Aborts are excluded, as the caller stopped those deliberately. | |
| 38 | + */ | |
| 39 | +export const isUnconfirmedRequest = (error: unknown): boolean => | |
| 40 | + isAxiosError(error) && !error.response && !isAbortError(error) | |
| 41 | + | |
| 42 | +/** | |
| 25 | 43 | * Explain a failed request in terms the reader can act on. |
| 26 | 44 | * |
| 27 | 45 | * An expired session is the common case worth naming: the snippet editor is a |
| 28 | 46 | * screen people leave open, and once the session lapses WordPress rejects every |
| @@ -35,9 +53,10 @@ | ||
| 35 | 53 | } |
| 36 | 54 | |
| 37 | 55 | if (!error.response) { |
| 38 | 56 | return __( |
| 39 | - 'The request did not reach your site. Check your connection, or whether a security plugin is blocking it.', | |
| 57 | + 'No response came back, so this could not be confirmed. The change may already have been saved — ' + | |
| 58 | + 'check in another tab before trying again.', | |
| 40 | 59 | 'code-snippets' |
| 41 | 60 | ) |
| 42 | 61 | } |
| 43 | 62 | |