Commit c7ba914f authored by Naoyuki Kanezawa's avatar Naoyuki Kanezawa Committed by GitHub

Handle runtime errors (#268)

* display runtime errors by error-debug

* server: fix status

* render Error component on client error

* server: render runtime errors of error template

* server: handle errors of error template on render404

* server: add a comment

* server: refactor renderJSON

* recover from runtime errors

* _error: check if xhr exists

* _error: improve client error

* _error: improve error message
parent a14cc667
...@@ -188,13 +188,17 @@ import React from 'react' ...@@ -188,13 +188,17 @@ import React from 'react'
export default class Error extends React.Component { export default class Error extends React.Component {
static getInitialProps ({ res, xhr }) { static getInitialProps ({ res, xhr }) {
const statusCode = res ? res.statusCode : xhr.status const statusCode = res ? res.statusCode : (xhr ? xhr.status : null)
return { statusCode } return { statusCode }
} }
render () { render () {
return ( return (
<p>An error { this.props.statusCode } occurred</p> <p>{
this.props.statusCode
? `An error ${this.props.statusCode} occurred on server`
: 'An error occurred on client'
]</p>
) )
} }
} }
......
...@@ -7,12 +7,17 @@ import App from '../lib/app' ...@@ -7,12 +7,17 @@ import App from '../lib/app'
import evalScript from '../lib/eval-script' import evalScript from '../lib/eval-script'
const { const {
__NEXT_DATA__: { component, props, ids, err } __NEXT_DATA__: { component, errorComponent, props, ids, err }
} = window } = window
const Component = evalScript(component).default const Component = evalScript(component).default
const ErrorComponent = evalScript(errorComponent).default
export const router = new Router(window.location.href, { Component, ctx: { err } }) export const router = new Router(window.location.href, {
Component,
ErrorComponent,
ctx: { err }
})
const headManager = new HeadManager() const headManager = new HeadManager()
const container = document.getElementById('__next') const container = document.getElementById('__next')
......
...@@ -16,6 +16,13 @@ const handlers = { ...@@ -16,6 +16,13 @@ const handlers = {
} }
next.router.reload(route) next.router.reload(route)
},
change (route) {
const { Component } = next.router.components[route] || {}
if (Component && Component.__route === '/_error-debug') {
// reload to recover from runtime errors
next.router.reload(route)
}
} }
} }
......
...@@ -3,15 +3,16 @@ import evalScript from './eval-script' ...@@ -3,15 +3,16 @@ import evalScript from './eval-script'
import shallowEquals from './shallow-equals' import shallowEquals from './shallow-equals'
export default class Router { export default class Router {
constructor (url, initialData) { constructor (url, { Component, ErrorComponent, ctx } = {}) {
const parsed = parse(url, true) const parsed = parse(url, true)
// represents the current component key // represents the current component key
this.route = toRoute(parsed.pathname) this.route = toRoute(parsed.pathname)
// set up the component cache (by route keys) // set up the component cache (by route keys)
this.components = { [this.route]: initialData } this.components = { [this.route]: { Component, ctx } }
this.ErrorComponent = ErrorComponent
this.pathname = parsed.pathname this.pathname = parsed.pathname
this.query = parsed.query this.query = parsed.query
this.subscriptions = new Set() this.subscriptions = new Set()
...@@ -38,13 +39,19 @@ export default class Router { ...@@ -38,13 +39,19 @@ export default class Router {
this.route = route this.route = route
this.set(getURL(), { ...data, props }) this.set(getURL(), { ...data, props })
}) })
.catch((err) => { .catch(async (err) => {
if (err.cancelled) return if (err.cancelled) return
// the only way we can appropriately handle const data = { Component: this.ErrorComponent, ctx: { err } }
// this failure is deferring to the browser const ctx = { ...data.ctx, pathname, query }
// since the URL has already changed const props = await this.getInitialProps(data.Component, ctx)
window.location.reload()
this.route = route
this.set(getURL(), { ...data, props })
console.error(err)
})
.catch((err) => {
console.error(err)
}) })
} }
...@@ -67,16 +74,25 @@ export default class Router { ...@@ -67,16 +74,25 @@ export default class Router {
let data let data
let props let props
let _err
try { try {
data = await this.fetchComponent(route) data = await this.fetchComponent(route)
const ctx = { ...data.ctx, pathname, query } const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx) props = await this.getInitialProps(data.Component, ctx)
} catch (err) { } catch (err) {
if (err.cancelled) return false if (err.cancelled) return false
throw err
data = { Component: this.ErrorComponent, ctx: { err } }
const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx)
_err = err
console.error(err)
} }
this.notify({ ...data, props }) this.notify({ ...data, props })
if (_err) throw _err
} }
back () { back () {
...@@ -100,13 +116,20 @@ export default class Router { ...@@ -100,13 +116,20 @@ export default class Router {
let data let data
let props let props
let _err
try { try {
data = await this.fetchComponent(route) data = await this.fetchComponent(route)
const ctx = { ...data.ctx, pathname, query } const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx) props = await this.getInitialProps(data.Component, ctx)
} catch (err) { } catch (err) {
if (err.cancelled) return false if (err.cancelled) return false
throw err
data = { Component: this.ErrorComponent, ctx: { err } }
const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx)
_err = err
console.error(err)
} }
if (getURL() !== url) { if (getURL() !== url) {
...@@ -115,6 +138,9 @@ export default class Router { ...@@ -115,6 +138,9 @@ export default class Router {
this.route = route this.route = route
this.set(url, { ...data, props }) this.set(url, { ...data, props })
if (_err) throw _err
return true return true
} }
......
...@@ -5,12 +5,12 @@ import style from 'next/css' ...@@ -5,12 +5,12 @@ import style from 'next/css'
export default class ErrorDebug extends React.Component { export default class ErrorDebug extends React.Component {
static getInitialProps ({ err }) { static getInitialProps ({ err }) {
const { message, module } = err const { name, message, stack, module } = err
return { message, path: module.rawRequest } return { name, message, stack, path: module ? module.rawRequest : null }
} }
render () { render () {
const { message, path } = this.props const { name, message, stack, path } = this.props
return <div className={styles.errorDebug}> return <div className={styles.errorDebug}>
<Head> <Head>
...@@ -21,8 +21,12 @@ export default class ErrorDebug extends React.Component { ...@@ -21,8 +21,12 @@ export default class ErrorDebug extends React.Component {
} }
`}} /> `}} />
</Head> </Head>
<div className={styles.heading}>Error in {path}</div> {path ? <div className={styles.heading}>Error in {path}</div> : null}
<pre className={styles.message} dangerouslySetInnerHTML={{ __html: ansiHTML(encodeHtml(message)) }} /> {
name === 'ModuleBuildError'
? <pre className={styles.message} dangerouslySetInnerHTML={{ __html: ansiHTML(encodeHtml(message)) }} />
: <pre className={styles.message}>{stack}</pre>
}
</div> </div>
} }
} }
......
import React from 'react' import React from 'react'
import style, { merge } from 'next/css' import style from 'next/css'
export default class Error extends React.Component { export default class Error extends React.Component {
static getInitialProps ({ res, xhr }) { static getInitialProps ({ res, xhr }) {
const statusCode = res ? res.statusCode : xhr.status const statusCode = res ? res.statusCode : (xhr ? xhr.status : null)
return { statusCode } return { statusCode }
} }
render () { render () {
const { statusCode } = this.props const { statusCode } = this.props
const title = statusCode === 404 ? 'This page could not be found' : 'Internal Server Error' const title = statusCode === 404
? 'This page could not be found'
: (statusCode ? 'Internal Server Error' : 'An unexpected error has occurred')
return <div className={merge(styles.error, styles['error_' + statusCode])}> return <div className={styles.error}>
<div className={styles.text}> <div className={styles.text}>
<h1 className={styles.h1}>{statusCode}</h1> {statusCode ? <h1 className={styles.h1}>{statusCode}</h1> : null}
<div className={styles.desc}> <div className={styles.desc}>
<h2 className={styles.h2}>{title}.</h2> <h2 className={styles.h2}>{title}.</h2>
</div> </div>
......
...@@ -17,6 +17,7 @@ export default class HotReloader { ...@@ -17,6 +17,7 @@ export default class HotReloader {
this.prevAssets = null this.prevAssets = null
this.prevChunkNames = null this.prevChunkNames = null
this.prevFailedChunkNames = null this.prevFailedChunkNames = null
this.prevChunkHashes = null
} }
async run (req, res) { async run (req, res) {
...@@ -66,6 +67,8 @@ export default class HotReloader { ...@@ -66,6 +67,8 @@ export default class HotReloader {
.reduce((a, b) => a.concat(b), []) .reduce((a, b) => a.concat(b), [])
.map((c) => c.name)) .map((c) => c.name))
const chunkHashes = new Map(compilation.chunks.map((c) => [c.name, c.hash]))
if (this.initialized) { if (this.initialized) {
// detect chunks which have to be replaced with a new template // detect chunks which have to be replaced with a new template
// e.g, pages/index.js <-> pages/_error.js // e.g, pages/index.js <-> pages/_error.js
...@@ -83,6 +86,16 @@ export default class HotReloader { ...@@ -83,6 +86,16 @@ export default class HotReloader {
const route = toRoute(relative(rootDir, n)) const route = toRoute(relative(rootDir, n))
this.send('reload', route) this.send('reload', route)
} }
for (const [n, hash] of chunkHashes) {
if (!this.prevChunkHashes.has(n)) continue
if (this.prevChunkHashes.get(n) === hash) continue
const route = toRoute(relative(rootDir, n))
// notify change to recover from runtime errors
this.send('change', route)
}
} }
this.initialized = true this.initialized = true
...@@ -90,6 +103,7 @@ export default class HotReloader { ...@@ -90,6 +103,7 @@ export default class HotReloader {
this.compilationErrors = null this.compilationErrors = null
this.prevChunkNames = chunkNames this.prevChunkNames = chunkNames
this.prevFailedChunkNames = failedChunkNames this.prevFailedChunkNames = failedChunkNames
this.prevChunkHashes = chunkHashes
}) })
this.webpackDevMiddleware = webpackDevMiddleware(compiler, { this.webpackDevMiddleware = webpackDevMiddleware(compiler, {
......
...@@ -18,7 +18,7 @@ export default class Server { ...@@ -18,7 +18,7 @@ export default class Server {
this.run(req, res) this.run(req, res)
.catch((err) => { .catch((err) => {
console.error(err) console.error(err)
res.status(500) res.statusCode = 500
res.end('error') res.end('error')
}) })
}) })
...@@ -73,96 +73,112 @@ export default class Server { ...@@ -73,96 +73,112 @@ export default class Server {
} }
async render (req, res) { async render (req, res) {
const { dir, dev } = this
const { pathname, query } = parse(req.url, true) const { pathname, query } = parse(req.url, true)
const ctx = { req, res, pathname, query } const ctx = { req, res, pathname, query }
const opts = { dir, dev }
let html const compilationErr = this.getCompilationError(req.url)
if (compilationErr) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err: compilationErr })
return
}
try {
await this.doRender(res, 200, req.url, ctx)
} catch (err) {
const compilationErr2 = this.getCompilationError('/_error')
if (compilationErr2) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err: compilationErr2 })
return
}
if (err.code !== 'ENOENT') {
console.error(err)
const url = this.dev ? '/_error-debug' : '/_error'
await this.doRender(res, 500, url, { ...ctx, err })
return
}
const err = this.getCompilationError(req.url)
if (err) {
res.statusCode = 500
html = await render('/_error-debug', { ...ctx, err }, opts)
} else {
try { try {
html = await render(req.url, ctx, opts) await this.doRender(res, 404, '/_error', { ...ctx, err })
} catch (err) { } catch (err2) {
const _err = this.getCompilationError('/_error') if (this.dev) {
if (_err) { await this.doRender(res, 500, '/_error-debug', { ...ctx, err: err2 })
res.statusCode = 500
html = await render('/_error-debug', { ...ctx, err: _err }, opts)
} else { } else {
if (err.code === 'ENOENT') { throw err2
res.statusCode = 404
} else {
console.error(err)
res.statusCode = 500
}
html = await render('/_error', { ...ctx, err }, opts)
} }
} }
} }
}
async doRender (res, statusCode, url, ctx) {
const { dir, dev } = this
// need to set statusCode before `render`
// since it can be used on getInitialProps
res.statusCode = statusCode
const html = await render(url, ctx, { dir, dev })
sendHTML(res, html) sendHTML(res, html)
} }
async renderJSON (req, res) { async renderJSON (req, res) {
const { dir } = this const compilationErr = this.getCompilationError(req.url)
const opts = { dir } if (compilationErr) {
await this.doRenderJSON(res, 500, '/_error-debug.json', compilationErr)
return
}
let json try {
await this.doRenderJSON(res, 200, req.url)
} catch (err) {
const compilationErr2 = this.getCompilationError('/_error.json')
if (compilationErr2) {
await this.doRenderJSON(res, 500, '/_error-debug.json', compilationErr2)
return
}
const err = this.getCompilationError(req.url) if (err.code === 'ENOENT') {
if (err) { await this.doRenderJSON(res, 404, '/_error.json')
res.statusCode = 500 } else {
json = await renderJSON('/_error-debug.json', opts) console.error(err)
json = { ...json, err: errorToJSON(err) } await this.doRenderJSON(res, 500, '/_error.json')
} else {
try {
json = await renderJSON(req.url, opts)
} catch (err) {
const _err = this.getCompilationError('/_error.json')
if (_err) {
res.statusCode = 500
json = await renderJSON('/_error-debug.json', opts)
json = { ...json, err: errorToJSON(_err) }
} else {
if (err.code === 'ENOENT') {
res.statusCode = 404
} else {
console.error(err)
res.statusCode = 500
}
json = await renderJSON('/_error.json', opts)
}
} }
} }
}
async doRenderJSON (res, statusCode, url, err) {
const { dir } = this
const json = await renderJSON(url, { dir })
if (err) {
json.err = errorToJSON(err)
}
const data = JSON.stringify(json) const data = JSON.stringify(json)
res.setHeader('Content-Type', 'application/json') res.setHeader('Content-Type', 'application/json')
res.setHeader('Content-Length', Buffer.byteLength(data)) res.setHeader('Content-Length', Buffer.byteLength(data))
res.statusCode = statusCode
res.end(data) res.end(data)
} }
async render404 (req, res) { async render404 (req, res) {
const { dir, dev } = this
const { pathname, query } = parse(req.url, true) const { pathname, query } = parse(req.url, true)
const ctx = { req, res, pathname, query } const ctx = { req, res, pathname, query }
const opts = { dir, dev }
let html const compilationErr = this.getCompilationError('/_error')
if (compilationErr) {
const err = this.getCompilationError('/_error') await this.doRender(res, 500, '/_error-debug', { ...ctx, err: compilationErr })
if (err) { return
res.statusCode = 500
html = await render('/_error-debug', { ...ctx, err }, opts)
} else {
res.statusCode = 404
html = await render('/_error', ctx, opts)
} }
sendHTML(res, html) try {
await this.doRender(res, 404, '/_error', ctx)
} catch (err) {
if (this.dev) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err })
} else {
throw err
}
}
} }
serveStatic (req, res, path) { serveStatic (req, res, path) {
......
...@@ -20,8 +20,15 @@ export async function render (url, ctx = {}, { ...@@ -20,8 +20,15 @@ export async function render (url, ctx = {}, {
const mod = await requireModule(join(dir, '.next', 'dist', 'pages', path)) const mod = await requireModule(join(dir, '.next', 'dist', 'pages', path))
const Component = mod.default || mod const Component = mod.default || mod
const props = await (Component.getInitialProps ? Component.getInitialProps(ctx) : {}) const [
const component = await read(join(dir, '.next', 'bundles', 'pages', path)) props,
component,
errorComponent
] = await Promise.all([
Component.getInitialProps ? Component.getInitialProps(ctx) : {},
read(join(dir, '.next', 'bundles', 'pages', path)),
read(join(dir, '.next', 'bundles', 'pages', dev ? '_error-debug' : '_error'))
])
const { html, css, ids } = renderStatic(() => { const { html, css, ids } = renderStatic(() => {
const app = createElement(App, { const app = createElement(App, {
...@@ -42,6 +49,7 @@ export async function render (url, ctx = {}, { ...@@ -42,6 +49,7 @@ export async function render (url, ctx = {}, {
css, css,
data: { data: {
component, component,
errorComponent,
props, props,
ids: ids, ids: ids,
err: (ctx.err && dev) ? errorToJSON(ctx.err) : null err: (ctx.err && dev) ? errorToJSON(ctx.err) : null
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment