mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-26 23:52:06 +00:00
feat(server): add custom HTTP headers into error response (#7214)
This commit is contained in:
parent
73541a576d
commit
1002d3f456
@ -10,7 +10,8 @@ export default ({ resources, options }) => async function errorMiddleware (err,
|
||||
const error = {
|
||||
statusCode: err.statusCode || 500,
|
||||
message: err.message || 'Nuxt Server Error',
|
||||
name: !err.name || err.name === 'Error' ? 'NuxtServerError' : err.name
|
||||
name: !err.name || err.name === 'Error' ? 'NuxtServerError' : err.name,
|
||||
headers: err.headers
|
||||
}
|
||||
|
||||
const sendResponse = (content, type = 'text/html') => {
|
||||
@ -21,6 +22,13 @@ export default ({ resources, options }) => async function errorMiddleware (err,
|
||||
res.setHeader('Content-Length', Buffer.byteLength(content))
|
||||
res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
|
||||
|
||||
// Error headers
|
||||
if (error.headers) {
|
||||
for (const name in error.headers) {
|
||||
res.setHeader(name, error.headers[name])
|
||||
}
|
||||
}
|
||||
|
||||
// Send Response
|
||||
res.end(content, 'utf-8')
|
||||
}
|
||||
|
@ -49,6 +49,7 @@ describe('server: errorMiddleware', () => {
|
||||
const params = createParams()
|
||||
const errorMiddleware = createErrorMiddleware(params)
|
||||
const error = new Error()
|
||||
error.headers = { 'Custom-Header': 'test' }
|
||||
const ctx = createServerContext()
|
||||
|
||||
await errorMiddleware(error, ctx.req, ctx.res, ctx.next)
|
||||
@ -56,10 +57,11 @@ describe('server: errorMiddleware', () => {
|
||||
expect(consola.error).toBeCalledWith(error)
|
||||
expect(ctx.res.statusCode).toEqual(500)
|
||||
expect(ctx.res.statusMessage).toEqual('NuxtServerError')
|
||||
expect(ctx.res.setHeader).toBeCalledTimes(3)
|
||||
expect(ctx.res.setHeader).toBeCalledTimes(4)
|
||||
expect(ctx.res.setHeader).nthCalledWith(1, 'Content-Type', 'text/html; charset=utf-8')
|
||||
expect(ctx.res.setHeader).nthCalledWith(2, 'Content-Length', Buffer.byteLength('error template'))
|
||||
expect(ctx.res.setHeader).nthCalledWith(3, 'Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
|
||||
expect(ctx.res.setHeader).nthCalledWith(4, 'Custom-Header', 'test')
|
||||
expect(params.resources.errorTemplate).toBeCalledTimes(1)
|
||||
expect(params.resources.errorTemplate).toBeCalledWith({
|
||||
status: 500,
|
||||
|
Loading…
Reference in New Issue
Block a user