Skip to content

Commit

Permalink
feat(next-drupal): translatePath - better flow on error response
Browse files Browse the repository at this point in the history
Cleaner flow and throw error with relevant message in DrupalClient.translatePath().
Fix test did not reproduce actual response.

BREAKING CHANGE:
Might break sites relying on response being the same in 404 than in 50x.

Fixes #687
  • Loading branch information
marcorcau committed Apr 13, 2024
1 parent 70d1f03 commit d3e6264
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
22 changes: 14 additions & 8 deletions packages/next-drupal/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -889,15 +889,21 @@ export class DrupalClient {
withAuth: options.withAuth,
})

if (response.status && response.status.toString().startsWith("5")) {
throw new Error(`Server error.`)
}

if (!response?.ok) {
// Do not throw errors here.
// Otherwise next.js will catch error and throw a 500.
// We want a 404.
return null
// Do not throw errors here when response is 404.
if (response.status === 404) {
return null
}

// Throw error in any other situation as response is not ok.
let errorMessage: string
try {
const responseJson = await response.json()
errorMessage = `${response.status} ${responseJson?.message}`
} catch (e) {
errorMessage = `${response.status} ${response.statusText}`
}
throw new Error(errorMessage)
}

const json = await response.json()
Expand Down
14 changes: 14 additions & 0 deletions packages/next-drupal/tests/DrupalClient/resource-methods.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,20 @@ describe("translatePath()", () => {
expect(path).toBeNull()
})

test("throws error for server errors", async () => {
console.log(BASE_URL)
const client = new DrupalClient(BASE_URL)

spyOnFetch({
responseBody: { message: "mocked internal server error" },
status: 500,
})

await expect(client.translatePath("/server-error")).rejects.toThrowError(
"500 mocked internal server error"
)
})

test("makes un-authenticated requests by default", async () => {
const client = new DrupalClient(BASE_URL)
const fetchSpy = jest.spyOn(client, "fetch")
Expand Down

0 comments on commit d3e6264

Please sign in to comment.