This website is a work in progress.

Handling page not found (404) and unknown URLs

Handling page not found (404) and unknown URLs

Because Phenomic will only generated during static build all possible known URLs for known resources, we need to handle the case where URLs requested does not match any result.

Everytime we use a star (*) and (sometimes) a parameter (:name) in a <Route definition, you will need to handle the case for data requested do not exist. With our previous example, we will need to add some case in multiple places.

Let's create a component to render the error

const PageError = ({ error }) => {
  const status = (error && error.status) || 404;
  const message = error && status !== 404 ? error.statusText : "Page not found";
 
  return (
    <div>
      <Head>
        <title>{message}</title>
      </Head>
      <h1>{message}</h1>
    </div>
  );
};

Now we need to catch all routes so we need to add a * after all routes

const routes = () => (
  <Router history={browserHistory}>
    <Route path="/" component={HomeContainer} />
    <Route path="/after/:after" component={HomeContainer} />
    <Route path="/blog/*" component={BlogPostContainer} />
    <Route path="*" component={PageError} />
  </Router>
);

Here it's almost done. We just miss all unknown error under /blog/* that won't be caught by the new route. So we will need to edit BlogPost to handle this kind of problem:

const BlogPost = ({ hasError, isLoading, page }) => {
  if (hasError) {
    return <PageError error={page.error} />;
  }
 
  return <Layout>{/* ...*/}</Layout>;
};

The fact that you have to handle each unknown routes that have a wildcard allows you to offer more accurate error pages.


Continue tutorial