{"record":{"id":"359047cbf9d40a3d","repo":"different-ai/openwork","slug":"failed-to-switch-organization-response-status","errorCode":null,"errorMessage":"Failed to switch organization (${response.status}).","messagePattern":"Failed to switch organization \\((.+?)\\)\\.","errorType":"http","errorClass":null,"httpStatus":null,"severity":"error","filePath":"ee/apps/den-web/app/(den)/dashboard/_providers/org-dashboard-provider.tsx","lineNumber":170,"sourceCode":"    if (!response.ok) {\n      throw new Error(getErrorMessage(payload, `Failed to load organizations (${response.status}).`));\n    }\n\n    return parseOrgListPayload(payload);\n  }\n\n  async function setActiveOrganization(input: { organizationId?: string | null; organizationSlug?: string | null }) {\n    const { response, payload } = await requestJson(\n      \"/api/auth/organization/set-active\",\n      {\n        method: \"POST\",\n        body: JSON.stringify(input),\n      },\n      12000,\n    );\n\n    if (!response.ok) {\n      throw new Error(getErrorMessage(payload, `Failed to switch organization (${response.status}).`));\n    }\n  }\n\n  async function loadOrgContext(organizationId: string, refreshRoles: boolean) {\n    const path = refreshRoles ? \"/v1/org?refreshRoles=true\" : \"/v1/org\";\n    const { response, payload } = await requestJson(\n      path,\n      { method: \"GET\", headers: { [ORG_SCOPE_HEADER]: organizationId } },\n      12000,\n    );\n    if (!response.ok) {\n      if (response.status === 404) {\n        throw new OrganizationNotFoundError(getErrorMessage(payload, `Failed to load organization (${response.status}).`));\n      }\n\n      throw new Error(getErrorMessage(payload, `Failed to load organization (${response.status}).`));\n    }\n","sourceCodeStart":152,"sourceCodeEnd":188,"githubUrl":"https://github.com/different-ai/openwork/blob/2b7df46e8ae1517d64c896c7793d2d52ec845669/ee/apps/den-web/app/(den)/dashboard/_providers/org-dashboard-provider.tsx#L152-L188","documentation":"setActiveOrganization POSTs the chosen organizationId/slug and throws this error when the response is not ok. The active-organization switch on the server did not persist, so subsequent org-scoped calls may still target the previous organization. The message carries the HTTP status unless the payload contains a server error message.","triggerScenarios":"POST switch endpoint returns 401 (session expired), 403 (no membership in the target org), 404 (organizationId/slug no longer exists or was deleted), 409/422 (org suspended or payload rejected), or 5xx from server faults.","commonSituations":"Switching to an org the user was just removed from; restoreDisplayedOrganization attempting to restore an org deleted in another tab; stale cached slug after an org rename.","solutions":["Read the status: 404 → clear the stored organizationId/slug (localStorage/cookie) and fall back to the default org from loadOrgDirectory.","403 → verify the user's membership/role in the target org on the server before offering the switch in the UI.","401 → redirect the user to sign-in; the session cookie has expired.","4xx/5xx with a payload message → surface getErrorMessage output to the user instead of the generic message.","After a failed restore, call refreshOrgData() to resync the directory instead of retrying the stale org."],"exampleFix":"// before\nawait restoreDisplayedOrganization(); // throws on deleted org\n// after\ntry {\n  await restoreDisplayedOrganization();\n} catch (err) {\n  clearStoredOrganization();\n  await refreshOrgData(); // fall back to first available org\n}","handlingStrategy":"fallback","validationCode":"// verify membership before switching\nconst orgs = await loadOrgDirectory();\nif (!orgs.some(o => o.slug === targetSlug || o.id === targetId)) throw new Error(\"Not a member of target org\");","typeGuard":"function isSwitchableOrg(org: unknown): org is { id: string; slug: string } {\n  return typeof org === \"object\" && org !== null && typeof (org as { id?: unknown }).id === \"string\" && typeof (org as { slug?: unknown }).slug === \"string\";\n}","tryCatchPattern":"try {\n  await setActiveOrganization({ organizationSlug: slug });\n} catch (err) {\n  clearStoredOrganization();\n  await refreshOrgData(); // fall back to a valid default org\n}","preventionTips":["Validate the target org against the directory before switching.","Purge stored org ids/slugs on sign-out and on 404.","After renames, resync slugs from the server rather than trusting cache.","Handle 403 by hiding orgs the user can't access in the switcher UI.","Catch restore failures at startup so a deleted org never blocks the dashboard."],"tags":["http","api","org-switch","den-web"],"backgroundTag":"http-request-failed","analyzedSha":"2b7df46e8ae1517d64c896c7793d2d52ec845669","analyzedAt":"2026-09-01T07:59:23.713Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}