Reputation: 656
So I have built a custom error page, to allow internationalization. This is working fine. The only way for me to test it though is to enter gibberish as route. For example: localhost:<port>/gibberish
so it will redirect me to the custom error page.
I have been trying to create a page named errortest
and inside that page, I want to throw an error with a given statusCode, so NextJs catches it and redirects to the custom error page.
Thing is, I have no idea how to do that.
Something along this:
const ErrorTest = () => {
//Throw Error
};
export default ErrorTest;
Upvotes: 4
Views: 15117
Reputation: 21
I ran into this issue as well, and I think the easiest way is to import the _error.js
page into another test page and render it with the status code of your choice. You can find this in the Next.js docs here. The code example you'll find looks like this:
import Error from 'next/error'
export async function getServerSideProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const errorCode = res.ok ? false : res.statusCode
const json = await res.json()
return {
props: { errorCode, stars: json.stargazers_count },
}
}
// Note the page returns your custom error page
export default function Page({ errorCode, stars }) {
if (errorCode) {
return <Error statusCode={errorCode} />
}
return <div>Next stars: {stars}</div>
}
You can import your custom error page into another page and make modifications there without having to run yarn build
and yarn start
. This is particularly useful if you want to update the styles or fix any issues which might come up during development (e.g. localization).
Upvotes: 2
Reputation: 678
You can create an exception in your component, e.g. null pointer. Though throwing an err should do as well.
Then you need to
yarn build && yarn start
When running the build you will see next.js showing your custom err page.
Upvotes: 1