Created
February 6, 2020 05:27
-
-
Save mqp/5572aaabd8d81f62c625f2b465b8b9f7 to your computer and use it in GitHub Desktop.
Fancy Express error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const app = require('express')(); | |
const fs = require('fs'); | |
// Resolves with a list of the filenames in dir, or rejects if dir doesn't exist or if something else goes wrong. | |
function readFileNames(dir) { | |
return new Promise((resolve, reject) => { | |
fs.readdir(dir, (err, files) => { | |
if (err) { | |
reject(err); | |
} else { | |
resolve(files); | |
} | |
}); | |
}); | |
} | |
// Returns a new async handler that is like the given one, but with promise rejections passed through to Express's "next" function. | |
function forwardErrors(handler) { | |
return (req, res, next) => handler(req, res).catch(next); | |
} | |
app.get('/', forwardErrors(async (req, res) => { | |
if (req.query.dir == null) { | |
throw new Error("A 'dir' query parameter must be provided."); | |
} | |
const results = await readFileNames(req.query.dir); | |
res.status(200).send(`Files in ${req.query.dir}:\n${results.join("\n")}`); | |
})); | |
app.use(function(error, req, res, next) { | |
res.status(500).send(error.toString()); | |
}); | |
app.listen(3000); | |
/* Example output: | |
sollux:express-error-test$ curl localhost:3000 | |
Error: A 'dir' query parameter must be provided. | |
sollux:express-error-test$ curl localhost:3000?dir=foo | |
Error: ENOENT: no such file or directory, scandir 'foo' | |
sollux:express-error-test$ curl localhost:3000?dir=. | |
Files in .: | |
index.js | |
node_modules | |
package-lock.json | |
package.json | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment