title: Next.JS: How to handle error in getInitialProps?
body: <p>I want to fetch data from an API, and if it fails I want it to render the <code>_error.js</code> page. My request depends on the router query. So if the user enters a wrong query the page is going to throw an error.</p>
  
  <p>If the request fails by throwing, I want my custom <code>_error.js</code> to be displayed.</p>
  
  <p>How do I achieve this?</p>
  
  <p>Here is my index page:</p>
  
  <pre class="lang-js prettyprint-override"><code>// pages/index.js
  
  import React from 'react'
  import PropTypes from 'prop-types'
  import fetch from 'isomorphic-unfetch'
  import Items from '../components/Items'
  import { API } from '../utils/config'
  
  const IndexPage = ({ items }) =&gt; {
    return (
      &lt;div&gt;
        &lt;Items items={items} /&gt;
      &lt;/div&gt;
    )
  }
  
  IndexPage.getInitialProps = async (context) =&gt; {
    const { query } = context
    const filter = query.filter || ''
    const name = query.name || ''
    const page = query.page || 1
    const response = await fetch(
      `${API}?${filter}=${name}&amp;page=${page}`,
    )
    const data = await response.json()
    return {
      items: data.items,
    }
  }
  
  export default IndexPage
  </code></pre>
  
  <p>my _app file:</p>
  
  <pre class="lang-js prettyprint-override"><code>// pages/_app.js
  
  import React from 'react'
  import Router from 'next/router'
  import Page from '../components/Page'
  
  const MyApp = (props) =&gt; {
    const { Component, pageProps } = props
    return (
      &lt;Page&gt;
        &lt;Component
          items={pageProps.items}
          query={pageProps.query}
          statusCode={pageProps.statusCode}
        /&gt;
      &lt;/Page&gt;
    )
  }
  
  export default MyApp
  </code></pre>