({
response,
result,
error,
}: {
response?: Response;
result?: unknown;
error?: unknown;
})
| 4 | import { ErrorCode, HTTPErrorCode } from './errorCodes'; |
| 5 | |
| 6 | export function apiErrorFactory({ |
| 7 | response, |
| 8 | result, |
| 9 | error, |
| 10 | }: { |
| 11 | response?: Response; |
| 12 | result?: unknown; |
| 13 | error?: unknown; |
| 14 | }): ServerError { |
| 15 | if (error && error instanceof Error && error.name === 'AbortError') { |
| 16 | return new AbortError(c('Error').t`Request aborted`); |
| 17 | } |
| 18 | |
| 19 | // Backend responses with 404 both in the response and body code. |
| 20 | // In such a case we want to stick to APIHTTPError to be very clear |
| 21 | // it is not NotFoundAPIError. |
| 22 | if (response?.status === HTTPErrorCode.NOT_FOUND || !result) { |
| 23 | const fallbackMessage = error instanceof Error ? error.message : c('Error').t`Something went wrong`; |
| 24 | const apiHttpError = new APIHTTPError(response?.statusText || fallbackMessage, response?.status || 500); |
| 25 | apiHttpError.cause = error; |
| 26 | return apiHttpError; |
| 27 | } |
| 28 | |
| 29 | const typedResult = result as { |
| 30 | Code?: number; |
| 31 | Error?: string; |
| 32 | Details?: object; |
| 33 | Exception?: string; |
| 34 | message?: string; |
| 35 | file?: string; |
| 36 | line?: number; |
| 37 | trace?: object; |
| 38 | }; |
| 39 | |
| 40 | const [code, message, details] = [ |
| 41 | typedResult.Code || 0, |
| 42 | typedResult.Error || c('Error').t`Something went wrong`, |
| 43 | typedResult.Details, |
| 44 | ]; |
| 45 | |
| 46 | const debug = typedResult.Exception |
| 47 | ? { |
| 48 | details: typedResult.Details, |
| 49 | exception: typedResult.Exception, |
| 50 | message: typedResult.message, |
| 51 | file: typedResult.file, |
| 52 | line: typedResult.line, |
| 53 | trace: typedResult.trace, |
| 54 | } |
| 55 | : undefined; |
| 56 | |
| 57 | switch (code) { |
| 58 | case ErrorCode.NOT_EXISTS: |
| 59 | return new NotFoundAPIError(message, code, details); |
| 60 | // ValidationError should be only when it is clearly user input error, |
| 61 | // otherwise it should be ServerError. |
| 62 | // Here we convert only general enough codes. Specific cases that are |
| 63 | // not clear from the code itself must be handled by each module |
no outgoing calls
no test coverage detected