storyblok / storyblok-astro

Astro SDK for Storyblok CMS
MIT License
163 stars 29 forks source link

Unable to handle 404 errors via src/pages/404.astro #574

Closed achapmandc2 closed 11 months ago

achapmandc2 commented 12 months ago

When I navigate to a slug that does not exist I expect my 404.astro page to load.

I have created a 404.astro within my pages folder, alongside [...slug].astro

This is the code for my [...slug].astro

---
import { useStoryblokApi } from '@storyblok/astro'
import StoryblokComponent from '@storyblok/astro/StoryblokComponent.astro'
import BaseLayout from '../layouts/BaseLayout.astro'
import isPreview from '../utils/isPreview'

export async function getStaticPaths() {
  const storyblokApi = useStoryblokApi()

  const { data } = await storyblokApi.get('cdn/links', {
    version: isPreview() ? 'draft' : 'published',
  })
  let links = data.links
  links = Object.values(links)

  return links.map((link : any) => {
    return {
      params: {
        slug: link.slug === 'home' ? undefined : link.slug,
      },
    }
  })
}

const { slug } = Astro.params

const storyblokApi = useStoryblokApi()

const { data } = await storyblokApi.get(
  `cdn/stories/${slug === undefined ? 'home' : slug}`,
  {
    version: isPreview() ? 'draft' : 'published',
  }
)

const story = data.story
---

<BaseLayout metadata={story.content.metadata}>
  <StoryblokComponent blok={story.content} />
</BaseLayout>

Expected Behavior

When a slug that does not exist is accessed I expect my 404.astro page to render

Current Behavior

In Production (Cloudflare) : Browser based 500 error In dev (localhost): I get the vite error page with the 404 error


Error: "{\"message\":\"Not Found\",\"status\":404,\"response\":\"This record could not be found\"}"
    at createSafeError (file:///home/aaronc/work/storyblok-astro/node_modules/astro/dist/core/errors/utils.js:64:19)
    at onError (file:///home/aaronc/work/storyblok-astro/node_modules/astro/dist/vite-plugin-astro-server/request.js:67:19)
    at runWithErrorHandling (file:///home/aaronc/work/storyblok-astro/node_modules/astro/dist/vite-plugin-astro-server/controller.js:67:19)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handleRequest (file:///home/aaronc/work/storyblok-astro/node_modules/astro/dist/vite-plugin-astro-server/request.js:47:3)```

## Steps to Reproduce
1. Run astro environment
2. Navigate to a slug that does not exist.
3. Error
achapmandc2 commented 11 months ago

Issue resolved, needed to wrap the get call in a try/catch and redirect manually to the 404 page on error.


  const { data } = await storyblokApi.get(
    `cdn/stories/${slug === undefined ? 'home' : slug}`,
    {
      version: isPreview() ? 'draft' : 'published',
    }
  )

  content = data.story.content
  metadata = data.story.content.metadata
}
catch {
  return Astro.redirect('/404')
}