简体   繁体   中英

Can't return props from getInitialProps when in custom error page

I have implemented a custom error page for my Next.js application by creating a custom _error.js file in my Pages folder, as explained in the docs. The problem is that any prop I return from getInitialProps turns out to be undefined.

So I tried keeping my custom _error.js page and putting the sample code in the docs:

import React from 'react'

class Error extends React.Component {
  static getInitialProps({ res, err }) {
    const statusCode = res ? res.statusCode : err ? err.statusCode : null
    return { statusCode }
  }

  render() {
    return (
      <p>
        {this.props.statusCode
          ? `An error ${this.props.statusCode} occurred on server`
          : 'An error occurred on client'}
      </p>
    )
  }
}

export default Error

Still no luck: this.props.statusCode logs as undefined.

The problem is I don't know where to look to debug the issue. In any other page in which I use getInitialProps it works just fine. What could be causing this behavior?

Several people are reporting this bug but it doesn't seem that it is being corrected. Zeit is using a custom HOC to handle errors :

https://spectrum.chat/next-js/general/error-handling-in-async-getinitialprops~99400c6c-0da8-4de5-aecd-2ecf122e8ad0?m=MTUzOTUyMTA1OTE0Mw==

It works fine with me.

Someone extended on this idea and published a NPM package .

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