Created
November 14, 2020 02:42
-
-
Save luizomf/1ddc58cd0be9473eb731710268563594 to your computer and use it in GitHub Desktop.
Express Async Errors
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
/* 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