Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const Layer = require('express/lib/router/layer');
Layer.prototype.handle_request = async function handle(req, res, next) {
var fn = this.handle;
if (fn.length > 3) {
// not a standard request handler
return next();
}
try {
await fn(req, res, next);
} catch (err) {
next(err);
}
};
const http = require('http');
const morgan = require('morgan');
require('./async_handle_request');
const app = require('express')();
app.get('/', (req, res, next) => {
res.json({ message: "ok" })
});
app.use(morgan('tiny'));
app.get('/ok', (req, res, next) => {
res.json({ message: "ok really" });
next();
});
app.get('/rejects', async (req, res, next) => {
throw new Error('I stink');
});
// Fallback handler
app.use((req, res) => {
if (!res.headersSent) {
res.status(404);
res.json({ error: 'Not Found' });
}
});
app.use(errorHandler);
/* istanbul ignore next */
// eslint-disable-next-line no-unused-vars
function errorHandler(err, req, res, next) {
// We must delegate to the Express error handler if the response has started
if (res.headersSent) {
return next(err);
}
// Try to detect common http codes that modules attach to errors
let code = parseInt(err.statusCode || err.code || err.status);
if (!(code >= 400 && code < 600)) {
code = 500;
}
res.status(code);
const message = err.message || http.STATUS_CODES[res.statusCode] || 'Internal Server Error';
res.json({ error: message });
}
module.exports = app;
if (require.main === module) {
const server = http.Server(app);
server.listen(process.env.PORT || 1337, function () {
const addr = this.address();
console.log(`Express server listening on port ${addr.port}`);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.