项目作者: Enkel-Digital

项目描述 :
Express JS generic error middlewares for HTTP 404 not found and 500 server internal error
高级语言: JavaScript
项目地址: git://github.com/Enkel-Digital/express-error-middlewares.git
创建时间: 2021-02-08T12:36:45Z
项目社区:https://github.com/Enkel-Digital/express-error-middlewares

开源协议:MIT License

下载


express-error-middlewares

Express JS generic error middlewares for HTTP 404 not found and 500 server internal error.
Created to skip always re-writing boilerplate code, and to make it easy to handle errors thrown from async route handlers.

Examples

Adding error middleware to express

  1. const express = require("express");
  2. const app = express();
  3. const { _404, _500 } = require("express-error-middlewares");
  4. app.use("/", require("./routes.js"));
  5. // Mount 404 and 500 error middleware last
  6. app.use(_404);
  7. app.use(_500);
  8. app.listen(3000, () => console.log("Server running on port 3000"));

Wrapping async route handlers to use _500 error handling middleware if anything throws asynchronously

  1. const express = require("express");
  2. const router = express.Router();
  3. const { asyncWrap } = require("express-error-middlewares");
  4. router.get(
  5. "/some-route",
  6. asyncWrap(async (req, res) => {
  7. const err = new Error("Throwing from an async route handler");
  8. // Set any code you want on the error object, will be 500 if left empty
  9. err.code = 501;
  10. // Any error thrown, either explicitly or from another function called within this async route handler
  11. // Will be caught, and passed to the error middleware handler
  12. throw err;
  13. res.status(200).json({ ok: true });
  14. })
  15. );
  16. module.exports = router;

License, Author and Contributing

This project is developed and made available under the “MIT” License
Pull requests are welcomed and open a issue if you have any questions!
If you more questions, contact us via email
Authors: