简体   繁体   中英

how to cleanly handle errors in nextjs getStaticProps

I'm very busy at the moment with building my first Next.JS application (Next and Strapi). Now everything is working but i'm curious about what the best way is to implement error handling when using getStaticProps.

I tried a few things myself (passing multiple props etc, but that all didn't work (typical unserialized JSON error). The thing I want to achieve is an error message on the page itself (eg /about) that no data was found. With an error message attached (statusCode).

I hope its possible, i did a lot research and found: https://github.com/vercel/next.js/pull/17755 this. But its not exactly what I'm looking for.

Thankyou. Justian Spijkerbosch

You can create custom 404 and 500 error pages . There is an option to show the statusCode however, you can tell Next to use the 404 page by returning notfound: true in getStaticProps .

If you return notfound: true , the statusCode will always show the 404 page, and you know the status code will be 404.

Here is a example of catching errors in getStaticProps - this will generate your page or show your custom error page that is designed to your specifications.

export const getStaticProps = async () => {
  try {
    const { data, errors } = await someQuery();
    if (errors || !data) {
      return { notFound: true };
    }
    return { props: { data } };
  } catch () {
    return { notFound: true };
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM