Skip to content

Instantly share code, notes, and snippets.

@luizomf
Created November 14, 2020 02:42
Show Gist options
  • Save luizomf/1ddc58cd0be9473eb731710268563594 to your computer and use it in GitHub Desktop.
Save luizomf/1ddc58cd0be9473eb731710268563594 to your computer and use it in GitHub Desktop.
Express Async Errors
/* Express Route Adapter */
const resolver = (handlerFn) => {
return (req, res, next) => {
return Promise.resolve(handlerFn(req, res, next))
.catch(e => next(e));
}
}
/* Errors */
class InternalServerError extends Error {
constructor(msg) {
super(msg);
this.name = 'InternalServerError';
this.statusCode = 500;
}
}
/* Interface Adapters */
const controller = async (req, res) => {
await new Promise(r => setTimeout(r, 3000));
throw new Error('Um erro qualquer.');
res.json({ok: 1});
}
/* Router */
const { Router } = require('express');
const router = new Router();
router.get('/', resolver(controller));
/* Server */
const app = require('express')();
app.use(router);
app.listen(3001, () => {
console.log(`Server running on port 3001`);
});
/* Middleware de tratamento de error */
app.use((error, req, res, next) => {
if (error && error.statusCode) {
res.status(error.statusCode).json({
statusCode: error.statusCode,
message: error.message
});
} else {
console.log(error);
}
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment