mirror of
https://github.com/nuxt/nuxt.git
synced 2025-01-27 13:52:38 +00:00
feat: json error response for application/json requests
This commit is contained in:
parent
67bd208c73
commit
e274db67a9
@ -277,22 +277,37 @@ export default class Renderer extends Tapable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
errorMiddleware (err, req, res, next) {
|
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
|
// Set Headers
|
||||||
res.statusCode = 500
|
res.statusCode = err.statusCode
|
||||||
res.setHeader('Content-Type', 'text/html; charset=utf-8')
|
res.statusMessage = err.message
|
||||||
res.setHeader('Content-Length', Buffer.byteLength(html))
|
res.setHeader('Content-Type', type + '; charset=utf-8')
|
||||||
|
res.setHeader('Content-Length', Buffer.byteLength(content))
|
||||||
|
|
||||||
// Send Response
|
// 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
|
// Use basic errors when debug mode is disabled
|
||||||
if (!this.options.render.debug) {
|
if (!this.options.render.debug) {
|
||||||
const html = this.resources.errorTemplate({
|
// Json format is compatible with Youch json responses
|
||||||
code: err.statusCode || 500,
|
const json = {
|
||||||
message: err.message || 'Nuxt Server Error'
|
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)
|
sendResponse(html)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -301,7 +316,11 @@ export default class Renderer extends Tapable {
|
|||||||
err.name = 'Nuxt Server Error'
|
err.name = 'Nuxt Server Error'
|
||||||
err.status = 500
|
err.status = 500
|
||||||
const youch = new Youch(err, req, this.readSource.bind(this))
|
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) {
|
async readSource (frame) {
|
||||||
|
Loading…
Reference in New Issue
Block a user