Unverified Commit 142bceb6 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure ENOENT error is not ignored when loading pages (#37486)

* Ensure ENOENT error is not ignored when loading pages

* Add a separate PageNotFoundError

* update tests
parent be5dedf6
...@@ -9,12 +9,12 @@ import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep' ...@@ -9,12 +9,12 @@ import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'
import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash' import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash'
import { removePagePathTail } from '../../shared/lib/page-path/remove-page-path-tail' import { removePagePathTail } from '../../shared/lib/page-path/remove-page-path-tail'
import { pageNotFoundError } from '../require'
import { reportTrigger } from '../../build/output' import { reportTrigger } from '../../build/output'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { serverComponentRegex } from '../../build/webpack/loaders/utils' import { serverComponentRegex } from '../../build/webpack/loaders/utils'
import { MIDDLEWARE_FILE, MIDDLEWARE_FILENAME } from '../../lib/constants' import { MIDDLEWARE_FILE, MIDDLEWARE_FILENAME } from '../../lib/constants'
import { getPageStaticInfo } from '../../build/analysis/get-page-static-info' import { getPageStaticInfo } from '../../build/analysis/get-page-static-info'
import { PageNotFoundError } from '../../shared/lib/utils'
export const ADDED = Symbol('added') export const ADDED = Symbol('added')
export const BUILDING = Symbol('building') export const BUILDING = Symbol('building')
...@@ -375,7 +375,7 @@ async function findPagePathData( ...@@ -375,7 +375,7 @@ async function findPagePathData(
pagePath = await findPageFile(rootDir, normalizedPagePath, extensions) pagePath = await findPageFile(rootDir, normalizedPagePath, extensions)
if (!pagePath) { if (!pagePath) {
throw pageNotFoundError(normalizedPagePath) throw new PageNotFoundError(normalizedPagePath)
} }
const pageUrl = ensureLeadingSlash( const pageUrl = ensureLeadingSlash(
...@@ -435,7 +435,7 @@ async function findPagePathData( ...@@ -435,7 +435,7 @@ async function findPagePathData(
page: normalizePathSep(page), page: normalizePathSep(page),
} }
} else { } else {
throw pageNotFoundError(normalizedPagePath) throw new PageNotFoundError(normalizedPagePath)
} }
} }
...@@ -444,6 +444,6 @@ function tryToNormalizePagePath(page: string) { ...@@ -444,6 +444,6 @@ function tryToNormalizePagePath(page: string) {
return normalizePagePath(page) return normalizePagePath(page)
} catch (err) { } catch (err) {
console.error(err) console.error(err)
throw pageNotFoundError(page) throw new PageNotFoundError(page)
} }
} }
...@@ -2,7 +2,12 @@ import './node-polyfill-fetch' ...@@ -2,7 +2,12 @@ import './node-polyfill-fetch'
import './node-polyfill-web-streams' import './node-polyfill-web-streams'
import type { Route } from './router' import type { Route } from './router'
import { CacheFs, DecodeError, execOnce } from '../shared/lib/utils' import {
CacheFs,
DecodeError,
execOnce,
PageNotFoundError,
} from '../shared/lib/utils'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin' import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import type RenderResult from './render-result' import type RenderResult from './render-result'
import type { FetchEventResult } from './web/types' import type { FetchEventResult } from './web/types'
...@@ -58,7 +63,7 @@ import BaseServer, { ...@@ -58,7 +63,7 @@ import BaseServer, {
stringifyQuery, stringifyQuery,
RoutingItem, RoutingItem,
} from './base-server' } from './base-server'
import { getPagePath, requireFontManifest, pageNotFoundError } from './require' import { getPagePath, requireFontManifest } from './require'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { loadComponents } from './load-components' import { loadComponents } from './load-components'
...@@ -706,7 +711,11 @@ export default class NextNodeServer extends BaseServer { ...@@ -706,7 +711,11 @@ export default class NextNodeServer extends BaseServer {
}, },
} }
} catch (err) { } catch (err) {
if (isError(err) && err.code !== 'ENOENT') throw err // we should only not throw if we failed to find the page
// in the pages-manifest
if (!(err instanceof PageNotFoundError)) {
throw err
}
} }
} }
return null return null
...@@ -1042,12 +1051,12 @@ export default class NextNodeServer extends BaseServer { ...@@ -1042,12 +1051,12 @@ export default class NextNodeServer extends BaseServer {
try { try {
foundPage = denormalizePagePath(normalizePagePath(page)) foundPage = denormalizePagePath(normalizePagePath(page))
} catch (err) { } catch (err) {
throw pageNotFoundError(page) throw new PageNotFoundError(page)
} }
let pageInfo = manifest.middleware[foundPage] let pageInfo = manifest.middleware[foundPage]
if (!pageInfo) { if (!pageInfo) {
throw pageNotFoundError(foundPage) throw new PageNotFoundError(foundPage)
} }
return { return {
......
...@@ -11,12 +11,7 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' ...@@ -11,12 +11,7 @@ import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path' import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin' import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import { PageNotFoundError } from '../shared/lib/utils'
export function pageNotFoundError(page: string): Error {
const err: any = new Error(`Cannot find module for page: ${page}`)
err.code = 'ENOENT'
return err
}
export function getPagePath( export function getPagePath(
page: string, page: string,
...@@ -47,7 +42,7 @@ export function getPagePath( ...@@ -47,7 +42,7 @@ export function getPagePath(
page = denormalizePagePath(normalizePagePath(page)) page = denormalizePagePath(normalizePagePath(page))
} catch (err) { } catch (err) {
console.error(err) console.error(err)
throw pageNotFoundError(page) throw new PageNotFoundError(page)
} }
const checkManifest = (manifest: PagesManifest) => { const checkManifest = (manifest: PagesManifest) => {
...@@ -75,7 +70,7 @@ export function getPagePath( ...@@ -75,7 +70,7 @@ export function getPagePath(
} }
if (!pagePath) { if (!pagePath) {
throw pageNotFoundError(page) throw new PageNotFoundError(page)
} }
return join(serverBuildPath, pagePath) return join(serverBuildPath, pagePath)
} }
......
...@@ -403,6 +403,15 @@ export const ST = ...@@ -403,6 +403,15 @@ export const ST =
export class DecodeError extends Error {} export class DecodeError extends Error {}
export class NormalizeError extends Error {} export class NormalizeError extends Error {}
export class PageNotFoundError extends Error {
code: string
constructor(page: string) {
super()
this.code = 'ENOENT'
this.message = `Cannot find module for page: ${page}`
}
}
export interface CacheFs { export interface CacheFs {
readFile(f: string): Promise<string> readFile(f: string): Promise<string>
......
...@@ -97,7 +97,7 @@ describe('Non-Standard NODE_ENV', () => { ...@@ -97,7 +97,7 @@ describe('Non-Standard NODE_ENV', () => {
join(appDir, '.next/static', file), join(appDir, '.next/static', file),
'utf8' 'utf8'
) )
if (content.match(/cannot find module/i)) { if (content.match(/cannot find module(?! for page)/i)) {
throw new Error(`${file} contains module not found error`) throw new Error(`${file} contains module not found error`)
} }
} }
......
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { check, renderViaHTTP } from 'next-test-utils'
describe('ENOENT during require', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/_app.js': `
import App from 'next/app'
if (typeof window === 'undefined') {
if (process.env.NEXT_PHASE !== 'phase-production-build') {
require('fs').readdirSync('non-existent-folder')
}
}
export default App
`,
'pages/index.js': `
export function getStaticProps() {
console.log('revalidate /')
return {
props: {
now: Date.now()
},
revalidate: 1
}
}
export default function Page() {
return <p>hello world</p>
}
`,
},
dependencies: {},
})
})
afterAll(() => next.destroy())
it('should show ENOENT error correctly', async () => {
await check(async () => {
await renderViaHTTP(next.url, '/')
console.error(next.cliOutput)
return next.cliOutput.includes('non-existent-folder')
? 'success'
: next.cliOutput
}, 'success')
expect(next.cliOutput).not.toContain('Cannot destructure property')
})
})
...@@ -3,11 +3,8 @@ ...@@ -3,11 +3,8 @@
import { join } from 'path' import { join } from 'path'
import { SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH } from 'next/constants' import { SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH } from 'next/constants'
import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path' import { normalizePagePath } from 'next/dist/shared/lib/page-path/normalize-page-path'
import { import { requirePage, getPagePath } from 'next/dist/server/require'
requirePage, import { PageNotFoundError } from 'next/dist/shared/lib/utils'
getPagePath,
pageNotFoundError,
} from 'next/dist/server/require'
const sep = '/' const sep = '/'
const distDir = join(__dirname, '_resolvedata') const distDir = join(__dirname, '_resolvedata')
...@@ -23,7 +20,7 @@ describe('pageNotFoundError', () => { ...@@ -23,7 +20,7 @@ describe('pageNotFoundError', () => {
it('Should throw error with ENOENT code', () => { it('Should throw error with ENOENT code', () => {
expect.assertions(1) expect.assertions(1)
try { try {
throw pageNotFoundError('test') throw new PageNotFoundError('test')
} catch (err) { } catch (err) {
// eslint-disable-next-line jest/no-try-expect // eslint-disable-next-line jest/no-try-expect
expect(err.code).toBe('ENOENT') expect(err.code).toBe('ENOENT')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment