From 7d60b2dea63f0059a35db5aaa99ebcfef318bad5 Mon Sep 17 00:00:00 2001 From: Miroslav Bajtos Date: Mon, 18 Nov 2013 15:36:13 +0100 Subject: [PATCH] Add loopback.urlNotFound() middleware. The middleware should be used as the last 3-parameter middleware (regular request handles) before any 4-parameter middleware (error handlers). This way a request to an URL not handled by any middleware is converted to a 404 error that can be handled by whatever error handling strategy is configured in the application. See senchalabs/connect#954 for more details. --- lib/middleware/urlNotFound.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 lib/middleware/urlNotFound.js diff --git a/lib/middleware/urlNotFound.js b/lib/middleware/urlNotFound.js new file mode 100644 index 00000000..9f9735e6 --- /dev/null +++ b/lib/middleware/urlNotFound.js @@ -0,0 +1,18 @@ +/** + * Export the middleware. + */ +module.exports = urlNotFound; + +/** + * Convert any request not handled so far to a 404 error + * to be handled by error-handling middleware. + * See discussion in Connect pull request #954 for more details + * https://github.com/senchalabs/connect/pull/954 + */ +function urlNotFound() { + return function raiseUrlNotFoundError(req, res, next) { + var error = new Error('Cannot ' + req.method + ' ' + req.url); + error.status = 404; + next(error); + } +}