{"record":{"id":"9c6b0e04ccdeaef4","repo":"ellite/Wallos","slug":"translate-network-response-error-http-response-status","errorCode":null,"errorMessage":"`${translate('network_response_error')} (HTTP ${response.status})`","messagePattern":"`(.+?) \\(HTTP (.+?)\\)`","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"scripts/settings.js","lineNumber":1381,"sourceCode":"\r\n  button.classList.add(\"hidden\");\r\n  spinner.classList.remove(\"hidden\");\r\n\r\n  fetch(endpoint, {\r\n    method: 'POST',\r\n    headers: {\r\n      'Content-Type': 'application/json',\r\n      'X-CSRF-Token': window.csrfToken,\r\n    }\r\n  })\r\n    .then(async response => {\r\n      const responseText = await response.text();\r\n      let data;\r\n\r\n      try {\r\n        data = JSON.parse(responseText);\r\n      } catch (error) {\r\n        throw new Error(`${translate('network_response_error')} (HTTP ${response.status})`);\r\n      }\r\n\r\n      if (!response.ok && !data.message) {\r\n        throw new Error(`${translate('network_response_error')} (HTTP ${response.status})`);\r\n      }\r\n\r\n      return data;\r\n    })\r\n    .then(data => {\r\n      if (data.success) {\r\n        showSuccessMessage(data.message);\r\n      } else {\r\n        showErrorMessage(data.message);\r\n      }\r\n    })\r\n    .catch(error => {\r\n      showErrorMessage(error.message || translate('unknown_error'));\r\n    })\r","sourceCodeStart":1363,"sourceCodeEnd":1399,"githubUrl":"https://github.com/ellite/Wallos/blob/52820e87ca5a6e105fdbb7f1c0c681bc0cfee2fd/scripts/settings.js#L1363-L1399","documentation":"This code first reads the response as text and attempts JSON.parse. If parsing fails (the body is not JSON at all), it throws a localized network_response_error annotated with the HTTP status. This is the 'malformed/non-JSON body' branch: the server replied, but not with the JSON the client expects (e.g. an HTML error page or empty body).","triggerScenarios":"The fetch resolves and response.text() returns a body that JSON.parse cannot parse: an HTML 500 error page from PHP, an empty body, plain-text output before/instead of JSON (e.g. a PHP warning printed before json_encode), or a redirect to an HTML login page.","commonSituations":"PHP fatal error or warning output corrupting the JSON body; session expiry redirecting the API call to an HTML login page; a reverse proxy serving its own HTML error page; calling the wrong URL that returns HTML.","solutions":["Inspect responseText in devtools or by logging it before parse to see what the server actually returned.","Check server error logs for PHP warnings/notices emitted before the JSON payload.","Ensure the session is alive and the request is not being redirected to an HTML page (check response.redirected / final URL).","Handle the case explicitly: treat non-JSON bodies as server-side failures and surface the status plus a snippet of the body to the user."],"exampleFix":"// before\ntry {\n  data = JSON.parse(responseText);\n} catch (error) {\n  throw new Error(`${translate('network_response_error')} (HTTP ${response.status})`);\n}\n// after\ntry {\n  data = JSON.parse(responseText);\n} catch (error) {\n  console.error('Non-JSON response:', responseText.slice(0, 200));\n  throw new Error(`${translate('network_response_error')} (HTTP ${response.status}, non-JSON body)`);\n}","handlingStrategy":"try-catch","validationCode":"function looksLikeJson(text) {\n  const t = text.trim();\n  return t.startsWith('{') || t.startsWith('[');\n}","typeGuard":null,"tryCatchPattern":"try {\n  data = JSON.parse(responseText);\n} catch (error) {\n  if (response.redirected || /<html/i.test(responseText)) {\n    window.location.reload(); // session likely expired, redirected to HTML page\n    return;\n  }\n  throw new Error(`${translate('network_response_error')} (HTTP ${response.status}, non-JSON body)`);\n}","preventionTips":["Disable PHP display_errors in production so warnings cannot corrupt JSON output.","Check response.redirected on fetch responses to detect session-expiry redirects to HTML pages.","Validate server endpoints return Content-Type: application/json.","Log the first bytes of unexpected bodies to spot proxy/HTML injection early."],"tags":["network","json","fetch","javascript"],"backgroundTag":"invalid-json-response","analyzedSha":"52820e87ca5a6e105fdbb7f1c0c681bc0cfee2fd","analyzedAt":"2026-09-13T14:09:30.873Z","contentChangedAt":"2026-09-13T14:09:30.873Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}