ExpressJSでのカスタム404/403ページ

通常のExpressJSの404エラーは

Cannot GET /hoge

のような簡素なものです。
今さら書く必要もありませんが、コンバージョンを上げるため、ユーザビリティのためにも独自にエラーページを設置しておくべきです。

という事で、ExpressJSでの実装方法をまとめておきます。
意図的に403/404エラーを起こさせるには、以下のようにres.send()を利用します。

res.send(403);
res.send(403, 'Forbidden');
res.send(404, 'Sorry, we cannot find that!');

もしくは、next()を使い、ルーティングを先に進め、マッチしない状態にさせます。

app.js

以下では、'/403'というリクエストがあった場合に403エラーを、'/'以外の場合は404エラーを起こさせています。
また、HTTPステータスコードを返しつつ(status())、Viewを作成して表示(render())させます。

app.get('/', routes.index);
app.get('*', function(req, res){
	if (req.path == '/403') {
		res.status(403).render('error', { title: '403' });
	} else {
		res.status(404).render('error', { title: '404' });
	}
});

この時、app.configure()内は、

app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);

の順でないと、public以下のCSS等のファイルにアクセスできなくなるので、注意が必要です。
※Viewは適当に

確認

では実行して試してみます。

$ wget http://localhost:3000/a
--2013-01-08 09:58:07--  http://localhost:3000/a
Resolving localhost... ::1, 127.0.0.1, fe80::1
Connecting to localhost|::1|:3000... failed: Connection refused.
Connecting to localhost|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response... 404 Not Found
2013-01-08 09:58:07 ERROR 404: Not Found.

$ wget http://localhost:3000/403
--2013-01-08 09:58:18--  http://localhost:3000/403
Resolving localhost... ::1, 127.0.0.1, fe80::1
Connecting to localhost|::1|:3000... failed: Connection refused.
Connecting to localhost|127.0.0.1|:3000... connected.
HTTP request sent, awaiting response... 403 Forbidden
2013-01-08 09:58:18 ERROR 403: Forbidden.

想定したエラーが返っているようです。
ブラウザで確認してみて、ViewやCSSが正しく表示されていればOKです。