From c621381e4ba6fa055b2707c9e24e28ed517ae641 Mon Sep 17 00:00:00 2001 From: Lennart Date: Thu, 3 Mar 2022 16:10:00 +0100 Subject: [PATCH] fix(gatsby): Better compile error handling (#35038) --- .../gatsby/src/bootstrap/get-config-file.ts | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/packages/gatsby/src/bootstrap/get-config-file.ts b/packages/gatsby/src/bootstrap/get-config-file.ts index da5d11444f2cd..dcca8f43cf2dd 100644 --- a/packages/gatsby/src/bootstrap/get-config-file.ts +++ b/packages/gatsby/src/bootstrap/get-config-file.ts @@ -32,16 +32,23 @@ export async function getConfigFile( configPath = path.join(`${siteDirectory}/${COMPILED_CACHE_DIR}`, configName) configFilePath = require.resolve(configPath) configModule = require(configFilePath) - } catch (err) { - if (!(err.code === `MODULE_NOT_FOUND`)) { - // If it's not the MODULE_NOT_FOUND error (which can happen if we're looking for JS files) - // It means it's an error with the compiled file + } catch (outerError) { + // Not all plugins will have a compiled file, so the err.message can look like this: + // "Cannot find module '/node_modules/gatsby-source-filesystem/.cache/compiled/gatsby-config'" + // But the compiled file can also have an error like this: + // "Cannot find module 'foobar'" + // So this is trying to differentiate between an error we're fine ignoring and an error that we should throw + const isModuleNotFoundError = outerError.code === `MODULE_NOT_FOUND` + const isThisFileRequireError = + outerError?.requireStack?.[0]?.includes(`get-config-file`) ?? true + + if (!(isModuleNotFoundError && isThisFileRequireError)) { report.panic({ id: `11902`, - error: err, + error: outerError, context: { configName, - message: err.message, + message: outerError.message, }, }) } @@ -51,7 +58,7 @@ export async function getConfigFile( try { configFilePath = require.resolve(configPath) configModule = require(configFilePath) - } catch (err) { + } catch (innerError) { // Only then hard fail const nearMatch = await fs.readdir(siteDirectory).then(files => files.find(file => { @@ -59,19 +66,19 @@ export async function getConfigFile( return isNearMatch(fileName, configName, distance) }) ) - if (!testRequireError(configPath, err)) { + if (!testRequireError(configPath, innerError)) { report.panic({ id: `10123`, - error: err, + error: innerError, context: { configName, - message: err.message, + message: innerError.message, }, }) } else if (nearMatch) { report.panic({ id: `10124`, - error: err, + error: innerError, context: { configName, nearMatch,