1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Fix error routes (#595)

* fix router error handlings

* respond with JSON when error occurs on JSON routes
This commit is contained in:
Naoyuki Kanezawa 2017-01-02 04:36:37 +09:00 committed by Guillermo Rauch
parent 0854855197
commit 897c60b4fd
3 changed files with 46 additions and 17 deletions

View file

@ -50,16 +50,19 @@ export default class Router extends EventEmitter {
error
} = await this.getRouteInfo(route, pathname, query)
if (error) {
if (error && error.cancelled) {
this.emit('routeChangeError', error, as)
// We don't need to throw here since the error is already logged by
// this.getRouteInfo
return
}
this.route = route
this.set(pathname, query, { ...data, props })
this.emit('routeChangeComplete', as)
if (error) {
this.emit('routeChangeError', error, as)
} else {
this.emit('routeChangeComplete', as)
}
}
update (route, Component) {
@ -87,13 +90,18 @@ export default class Router extends EventEmitter {
error
} = await this.getRouteInfo(route, pathname, query)
if (error && error.cancelled) {
this.emit('routeChangeError', error, url)
return
}
this.notify({ ...data, props })
if (error) {
this.emit('routeChangeError', error, url)
throw error
}
this.notify({ ...data, props })
this.emit('routeChangeComplete', url)
}
@ -127,9 +135,9 @@ export default class Router extends EventEmitter {
data, props, error
} = await this.getRouteInfo(route, pathname, query)
if (error) {
if (error && error.cancelled) {
this.emit('routeChangeError', error, as)
throw error
return false
}
changeState()
@ -137,6 +145,11 @@ export default class Router extends EventEmitter {
this.route = route
this.set(pathname, query, { ...data, props })
if (error) {
this.emit('routeChangeError', error, as)
throw error
}
this.emit('routeChangeComplete', as)
return true

View file

@ -213,6 +213,30 @@ export default class Server {
return renderErrorJSON(err, req, res, this.renderOpts)
}
async serveStaticWithGzip (req, res, path) {
this._serveStatic(req, res, () => {
return serveStaticWithGzip(req, res, path)
})
}
serveStatic (req, res, path) {
this._serveStatic(req, res, () => {
return serveStatic(req, res, path)
})
}
async _serveStatic (req, res, fn) {
try {
await fn()
} catch (err) {
if (err.code === 'ENOENT') {
this.render404(req, res)
} else {
throw err
}
}
}
getCompilationError (page) {
if (!this.hotReloader) return

View file

@ -169,15 +169,7 @@ export async function serveStaticWithGzip (req, res, path) {
export function serveStatic (req, res, path) {
return new Promise((resolve, reject) => {
send(req, path)
.on('error', (err) => {
if (err.code === 'ENOENT') {
res.statusCode = 404
res.end('Not Found')
resolve()
} else {
reject(err)
}
})
.on('error', reject)
.pipe(res)
.on('finish', resolve)
})