feat: json error response for application/json requests

This commit is contained in:
Pooya Parsa 2017-08-05 12:04:33 +04:30
parent 67bd208c73
commit e274db67a9

View File

@ -277,22 +277,37 @@ export default class Renderer extends Tapable {
}
errorMiddleware (err, req, res, next) {
const sendResponse = html => {
// ensure statusCode and message
err.statusCode = err.statusCode || 500
err.message = err.message || 'Nuxt Server Error'
const sendResponse = (content, type = 'text/html') => {
// Set Headers
res.statusCode = 500
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.setHeader('Content-Length', Buffer.byteLength(html))
res.statusCode = err.statusCode
res.statusMessage = err.message
res.setHeader('Content-Type', type + '; charset=utf-8')
res.setHeader('Content-Length', Buffer.byteLength(content))
// Send Response
res.end(html, 'utf8')
res.end(content, 'utf-8')
}
// Check if request accepts JSON
const isJson = (req.headers.accept || '').toLowerCase().includes('application/json')
// Use basic errors when debug mode is disabled
if (!this.options.render.debug) {
const html = this.resources.errorTemplate({
code: err.statusCode || 500,
message: err.message || 'Nuxt Server Error'
})
// Json format is compatible with Youch json responses
const json = {
status: err.statusCode,
message: err.message,
name: 'Nuxt Server Error'
}
if (isJson) {
sendResponse(JSON.stringify(json, undefined, 2), 'text/json')
return
}
const html = this.resources.errorTemplate(json)
sendResponse(html)
return
}
@ -301,7 +316,11 @@ export default class Renderer extends Tapable {
err.name = 'Nuxt Server Error'
err.status = 500
const youch = new Youch(err, req, this.readSource.bind(this))
youch.toHTML().then(html => { sendResponse(html) })
if (isJson) {
youch.toJSON().then(json => { sendResponse(JSON.stringify(json, undefined, 2), 'text/json') })
} else {
youch.toHTML().then(html => { sendResponse(html) })
}
}
async readSource (frame) {