エラーページ - Express.js

  • 作成日:
  • 最終更新日:2025/10/11

エラーページの設定

app.jserror handlerの部分を以下のように編集します。

app.js

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  if(app.get('env') === 'development'){
res.status(err.status || 500);
res.render('error');
  } else {
// render the error page
res.status(err.status || 500);
console.log(res.statusCode)
if(res.statusCode == 404){
  return res.render('error/404');
} else {
  return res.render('error/500')
}
  }
});

views/errorディレクトリに「 404.ejs と 500.ejs 」のファイルを作成します。

views/error/404.ejs

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>エラー</title>
  <style>
h1{
  text-align: center;
}
p {
  text-align: center;
}
  </style>
</head>
<body>
  <h1>404</h1>
  <p>Not Found</p>
</body>
</html>

views/error/500.ejs

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>エラー</title>
  <style>
h1{
  text-align: center;
}
p {
  text-align: center;
}
  </style>
</head>
<body>
  <h1>500</h1>
  <p>Internal Server Error</p>
</body>
</html>

app.js の内容だと「 development 」だとエラーページを表示することができない為、環境変数に「 production 」を設定して確認する必要があります。

「 production 」に設定してエラーページを確認する

package.jsonを以下のように設定します。

package.json

{
  "name": "myapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
"start": "node --env-file=conf/.env ./bin/www",
"product": "node --env-file=conf/.env_product ./bin/www"
  },
  "dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ejs": "^3.1.10",
"express": "^5.0.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1"
  }
}
  • exapp
    • ... 中略 ...
    • conf
      • .env
      • .env_product
    • ... 中略 ...
    • package.json

.env_productの内容を以下のようにします。

NODE_ENV="production"

以下のコマンドを実行すると.env_productを読み込んで、アプリが起動します。

npm run product

npm startで起動した場合は、.envを読み込み、「 development 」で起動します。

「 production 」、「 development 」どちらが設定されている確認するには、app.jsに、以下のように記述します。

アプリを起動したコマンドプロンプトに「 production 」、「 development 」のどちらかが表示されます。

console.log(app.get('env'));
module.exports = app; // 最終行