renderer: errorMiddleware

Catch all middleware errors
This commit is contained in:
Pooya Parsa 2017-06-20 16:34:20 +04:30
parent daa50e4efb
commit b6544637e0
2 changed files with 30 additions and 18 deletions

View File

@ -22,7 +22,7 @@ export default class Nuxt extends Tapable {
this.renderer = new Renderer(this)
// Backward compatibility
this.render = (...args) => this.renderer.app(...args)
this.render = this.renderer.app
this.renderRoute = this.renderer.renderRoute.bind(this.renderer)
this.renderAndGetWindow = this.renderer.renderAndGetWindow.bind(this.renderer)

View File

@ -45,6 +45,10 @@ export default class Renderer extends Tapable {
errorTemplate: parseTemplate('<pre>{{ stack }}</pre>') // Will be loaded on ready
}
// Bind middleware to this context
this.nuxtMiddleware = this.nuxtMiddleware.bind(this)
this.errorMiddleware = this.errorMiddleware.bind(this)
// Initialize
/* istanbul ignore if */
if (nuxt.initialized) {
@ -220,10 +224,13 @@ export default class Renderer extends Tapable {
}
// Finally use nuxtMiddleware
this.useMiddleware(this.nuxtMiddleware.bind(this))
this.useMiddleware(this.nuxtMiddleware)
// Error middleware for errors that occurred in middleware that declared above
this.useMiddleware(this.errorMiddleware)
}
async nuxtMiddleware (req, res) {
async nuxtMiddleware (req, res, next) {
// Get context
const context = getContext(req, res)
res.statusCode = 200
@ -271,11 +278,17 @@ export default class Renderer extends Tapable {
res.end(html, 'utf8')
return html
} catch (err) {
next(this.errorMiddleware(err, req, res, next, context))
}
}
async errorMiddleware (err, req, res, next, context) {
/* istanbul ignore if */
if (context.redirected) {
if (context && context.redirected) {
console.error(err) // eslint-disable-line no-console
return err
}
// Render error template
const html = this.resources.errorTemplate({
error: err,
@ -288,7 +301,6 @@ export default class Renderer extends Tapable {
res.end(html, 'utf8')
return err
}
}
async renderRoute (url, context = {}) {
/* istanbul ignore if */