(response, context = 'API call')
| 18 | * @throws {Error} Throws a formatted error with status and potentially parsed details. |
| 19 | */ |
| 20 | export const handleApiError = async (response, context = 'API call') => { |
| 21 | let errorMsg = `${context} failed: ${response.status} ${response.statusText}`; |
| 22 | let errorData = null; |
| 23 | try { |
| 24 | // Attempt to parse error detail from backend JSON |
| 25 | errorData = await response.json(); |
| 26 | const detail = errorData.detail || (typeof errorData === 'string' ? errorData : null) || JSON.stringify(errorData); |
| 27 | if (detail) { |
| 28 | errorMsg = `${context} failed: ${detail}`; |
| 29 | } |
| 30 | } catch (jsonError) { |
| 31 | // If JSON parsing fails, try reading as text |
| 32 | try { |
| 33 | const textError = await response.text(); |
| 34 | if (textError) { |
| 35 | errorMsg = `${context} failed: ${textError}`; |
| 36 | } |
| 37 | } catch (textError) { |
| 38 | // Ignore text reading error, stick with the status text message |
| 39 | } |
| 40 | } |
| 41 | console.error(`API Error during ${context}:`, { |
| 42 | status: response.status, |
| 43 | statusText: response.statusText, |
| 44 | data: errorData, |
| 45 | message: errorMsg |
| 46 | }); |
| 47 | const error = new Error(errorMsg); |
| 48 | error.status = response.status; |
| 49 | error.data = errorData; // Attach parsed data if available |
| 50 | throw error; |
| 51 | }; |
no outgoing calls
no test coverage detected