0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

fix: throw a useful error if rendering undefined entry (#12113)

* fix: throw a useful error if rendering undefined entry

* Update .changeset/wise-pumas-fry.md

Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>

---------

Co-authored-by: Emanuele Stoppa <my.burning@gmail.com>
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
This commit is contained in:
Matt Kane 2024-10-03 19:55:55 +01:00 committed by GitHub
parent 4dc00cc7c9
commit a54e520d3c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 42 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Adds a helpful error when attempting to render an undefined collection entry

View file

@ -436,7 +436,11 @@ function updateImageReferencesInData<T extends Record<string, unknown>>(
export async function renderEntry(
entry: DataEntry | { render: () => Promise<{ Content: AstroComponentFactory }> },
) {
if (entry && 'render' in entry) {
if (!entry) {
throw new AstroError(AstroErrorData.RenderUndefinedEntryError);
}
if ('render' in entry) {
// This is an old content collection entry, so we use its render method
return entry.render();
}

View file

@ -1410,6 +1410,17 @@ export const UnknownContentCollectionError = {
title: 'Unknown Content Collection Error.',
} satisfies ErrorData;
/**
* @docs
* @description
* Astro tried to render a content collection entry that was undefined. This can happen if you try to render an entry that does not exist.
*/
export const RenderUndefinedEntryError = {
name: 'RenderUndefinedEntryError',
title: 'Attempted to render an undefined content collection entry.',
hint: 'Check if the entry is undefined before passing it to `render()`',
} satisfies ErrorData;
/**
* @docs
* @description

View file

@ -317,5 +317,12 @@ describe('Content Layer', () => {
assert.ok(updated.fileLoader[0].data.temperament.includes('Bouncy'));
await fixture.resetAllFiles();
});
it('returns an error if we render an undefined entry', async () => {
const res = await fixture.fetch('/missing');
const text = await res.text();
assert.equal(res.status, 500);
assert.ok(text.includes('RenderUndefinedEntryError'));
});
});
});

View file

@ -0,0 +1,14 @@
---
import { getEntry, render } from "astro:content"
// Skipping the broken page in production so the build doesn't fail
if(import.meta.env.PROD) {
return new Response(null, { status: 404 })
}
const entry = await getEntry("spacecraft", "missing")
const { Content } = await render(entry)
---
<Content />