Skip to content

Commit

Permalink
[fix] Handle 4xx and 5xx statuses without requiring Error instance (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
damain committed Jul 15, 2021
1 parent 3410b54 commit 41da1eb
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/quiet-waves-compete.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Handle 4xx and 5xx statuses without requiring `Error` instance
14 changes: 11 additions & 3 deletions packages/kit/src/runtime/load.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@
* @returns {import('types/internal').NormalizedLoadOutput}
*/
export function normalize(loaded) {
// TODO should this behaviour be dev-only?
const has_error_status =
loaded.status && loaded.status >= 400 && loaded.status <= 599 && !loaded.redirect;
if (loaded.error || has_error_status) {
const status = loaded.status;

if (!loaded.error && has_error_status) {
return {
status,
error: new Error()
};
}

if (loaded.error) {
const error = typeof loaded.error === 'string' ? new Error(loaded.error) : loaded.error;
const status = loaded.status;

if (!(error instanceof Error)) {
return {
Expand Down
25 changes: 25 additions & 0 deletions packages/kit/test/apps/basics/src/routes/errors/_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,4 +211,29 @@ export default function (test, is_dev) {
assert.ok(!has_stack_trace, 'Stack trace is visible');
}
});

test(
'server-side 4xx status without error from load()',
'/errors/load-status-without-error-server',
async ({ page, response }) => {
assert.equal(await page.textContent('footer'), 'Custom layout');
assert.equal(await page.textContent('#message'), 'This is your custom error page saying: ""');
assert.equal(response.status(), 401);
}
);

test(
'client-side 4xx status without error from load()',
'/errors/load-status-without-error-client',
async ({ page, js }) => {
if (js) {
assert.equal(await page.textContent('footer'), 'Custom layout');
assert.equal(
await page.textContent('#message'),
'This is your custom error page saying: ""'
);
assert.equal(await page.innerHTML('h1'), '401', 'Should set status code');
}
}
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<script context="module">
export async function load() {
if (typeof window !== 'undefined') {
return { status: 401 };
}
return {};
}
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script context="module">
/** @type {import('@sveltejs/kit').Load} */
export async function load() {
return { status: 401 };
}
</script>

0 comments on commit 41da1eb

Please sign in to comment.