Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle errors of React lifecycle methods #661

Merged
merged 2 commits into from
Jan 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion client/next-dev.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import 'react-hot-loader/patch'
import * as next from './next'
import patch from './patch-react'

// apply patch first
patch((err) => {
console.error(err)
next.renderError(err)
})

const next = require('./next')
window.next = next
30 changes: 27 additions & 3 deletions client/next.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createElement } from 'react'
import { render } from 'react-dom'
import ReactDOM from 'react-dom'
import HeadManager from './head-manager'
import { rehydrate } from '../lib/css'
import { createRouter } from '../lib/router'
Expand Down Expand Up @@ -29,7 +29,31 @@ export const router = createRouter(pathname, query, {

const headManager = new HeadManager()
const container = document.getElementById('__next')
const appProps = { Component, props, router, headManager }
const defaultProps = { Component, ErrorComponent, props, router, headManager }

if (ids && ids.length) rehydrate(ids)
render(createElement(App, appProps), container)

render()

export function render (props = {}) {
try {
doRender(props)
} catch (err) {
renderError(err)
}
}

export async function renderError (err) {
const { pathname, query } = router
const props = await ErrorComponent.getInitialProps({ err, pathname, query })
try {
doRender({ Component: ErrorComponent, props })
} catch (err2) {
console.error(err2)
}
}

function doRender (props) {
const appProps = { ...defaultProps, ...props }
ReactDOM.render(createElement(App, appProps), container)
}
62 changes: 62 additions & 0 deletions client/patch-react.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// monkeypatch React for fixing https://github.com/facebook/react/issues/2461
// based on https://gist.github.com/Aldredcz/4d63b0a9049b00f54439f8780be7f0d8

import React from 'react'

let patched = false

export default (handleError = () => {}) => {
if (patched) {
throw new Error('React is already monkeypatched')
}

patched = true

const { createElement } = React

React.createElement = function (Component, ...rest) {
if (typeof Component === 'function') {
const { prototype } = Component
if (prototype && prototype.render) {
prototype.render = wrapRender(prototype.render)
} else {
// stateless component
Component = wrapRender(Component)
}
}

return createElement.call(this, Component, ...rest)
}

const { Component: { prototype: componentPrototype } } = React
const { forceUpdate } = componentPrototype

componentPrototype.forceUpdate = function (...args) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why attempt to re-wrap in forceUpdate()?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure but it's for hot reload according to the original code.(https://gist.github.com/Aldredcz/4d63b0a9049b00f54439f8780be7f0d8)

if (this.render) {
this.render = wrapRender(this.render)
}
return forceUpdate.apply(this, args)
}

function wrapRender (render) {
if (render.__wrapped) {
return render.__wrapped
}

const _render = function (...args) {
try {
return render.apply(this, args)
} catch (err) {
handleError(err)
return null
}
}

// copy all properties
Object.assign(_render, render)

render.__wrapped = _render.__wrapped = _render

return _render
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will this break compat layers ? cc @developit @trueadm

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see anything that would cause issues in here. It's actually a pretty decent idea and something I've had on my backlog for a while. Only complaint I have is that this wraps every single component in a try/catch, which won't be great for performance. If it's only done in dev mode that might be workable though.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@developit I thought try/catch wasn't an issue anymore for performance in modern engines

Copy link
Member

@rauchg rauchg Jan 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

¯\(ツ)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is dev only though

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:O

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The advantage of shipping this in the prod version would be preventing surprises, and handling runtime errors for the end user better. Food for thought.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed! In my own work, I'm looking at installing this error boundary in a subset of components at key points in the tree for production. Those can generate useful error logs!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think we would probably catch at the page boundary for Next

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw - might be useful to pass a reference to this or the constructor to handleError so it could show which component's render bailed

}
19 changes: 17 additions & 2 deletions lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default class App extends Component {
try {
this.setState(state)
} catch (err) {
console.error(err)
this.handleError(err)
}
}

Expand All @@ -37,7 +37,7 @@ export default class App extends Component {
try {
this.setState(state)
} catch (err) {
console.error(err)
this.handleError(err)
}
})
}
Expand All @@ -58,6 +58,21 @@ export default class App extends Component {
<Component {...props} />
</AppContainer>
}

async handleError (err) {
console.error(err)

const { router, ErrorComponent } = this.props
const { pathname, query } = router
const props = await ErrorComponent.getInitialProps({ err, pathname, query })
const state = propsToState({ Component: ErrorComponent, props, router })

try {
this.setState(state)
} catch (err2) {
console.error(err2)
}
}
}

function propsToState (props) {
Expand Down