Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes 404 no longer returned when error with code ENOENT is thrown. #11480

Closed
wants to merge 8 commits into from
11 changes: 8 additions & 3 deletions packages/next/next-server/server/next-server.ts
Expand Up @@ -1237,9 +1237,14 @@ export default class Server {
}
}
} catch (err) {
this.logError(err)
res.statusCode = 500
return await this.renderErrorToHTML(err, req, res, pathname, query)
if (err && err.code === 'ENOENT') {
res.statusCode = 404
return await this.renderErrorToHTML(null, req, res, pathname, query)
} else {
this.logError(err)
res.statusCode = 500
return await this.renderErrorToHTML(err, req, res, pathname, query)
}
}

res.statusCode = 404
Expand Down
2 changes: 1 addition & 1 deletion packages/next/next-server/server/render.tsx
Expand Up @@ -637,7 +637,7 @@ export async function renderToHTML(
;(renderOpts as any).pageData = props
}
} catch (err) {
if (isDataReq || !dev || !err) throw err
if (isDataReq || !dev || !err || err.code === 'ENOENT') throw err
ctx.err = err
renderOpts.err = err
console.error(err)
Expand Down
9 changes: 9 additions & 0 deletions test/integration/custom-error/pages/throw-404.js
@@ -0,0 +1,9 @@
const Page = () => 'hi'

Page.getInitialProps = () => {
const error = new Error('to 404 we go')
error.code = 'ENOENT'
throw error
}

export default Page
12 changes: 10 additions & 2 deletions test/integration/custom-error/test/index.test.js
Expand Up @@ -17,10 +17,16 @@ const nextConfig = join(appDir, 'next.config.js')
let appPort
let app

const runTests = () => {
const runTests = isDev => {
it('renders custom _error successfully', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Custom error/)
expect(html).toMatch(isDev ? /oof/ : /Custom error/)
})

it('renders 404 page when ENOENT error is thrown', async () => {
const html = await renderViaHTTP(appPort, '/throw-404')
expect(html).toContain('Custom error')
expect(html).not.toContain('to 404 we go')
})
}

Expand Down Expand Up @@ -56,6 +62,8 @@ describe('Custom _error', () => {
expect(html).toContain('An error 404 occurred on server')
expect(stderr).toMatch(customErrNo404Match)
})

runTests(true)
})

describe('production mode', () => {
Expand Down