Skip to content

Instantly share code, notes, and snippets.

@mqp
Created February 6, 2020 05:28
Show Gist options
  • Save mqp/59f88d298b267a094b49a7d717ea3605 to your computer and use it in GitHub Desktop.
Save mqp/59f88d298b267a094b49a7d717ea3605 to your computer and use it in GitHub Desktop.
Simple Express error handling
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);
}
});
});
}
app.get('/', async (req, res, next) => {
try {
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")}\n`);
} catch (err) {
next(err);
}
});
app.use(function(error, req, res, next) {
res.status(500).send(error.toString() + '\n');
});
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