zoukankan      html  css  js  c++  java
  • [Express] Handle Syncronous and Asyncronous Errors in Express

    When express App run syncronous code:

    app.get("/test", (req, res) => {
      throw new Error("Oh no! The world has ended!");
    });

    Those code works fine.

    But when run Asyncronous code:

    app.get("/test", async (req, res) => {
      throw new Error("Oh no! The world has ended!");
    });

    It has problem. 

    1. Using 'next':

    app.get("/test", async (req, res, next) => {
      next(throw new Error("Oh no! The world has ended!"));
    });

    2. Using try/catch:

    app.get("/test", async (req, res) => {
        try {
              throw new Error("Oh no! The world has ended!");
        } catch(error) {
            next(error)
        }
    });

    3. Library:  express-async-errors

    const express = require("express");
    const app = express();
    require("express-async-errors");
    
    app.get("/test", async (req, res) => {
      throw new Error("Oh no! The world has ended!");
    });

    4. Custom middleware:

    const { errorHandling } = require("./utils/error");
    
    app.get("/test", async (req, res) => {
      throw new Error("Oh no! The world has ended!");
    });
    
    app.use(errorHandling); // keep it as last step
    
    app.listen(3001, function () {
      console.log("Server started.");
    });
    function errorHandling(error, req, res, next) {
      if (res.headersSent) {
        next(error);
      } else {
        res.status(500);
        res.json({
          message: error.message,
          ...(process.env.NODE_ENV === "production"
            ? null
            : { stack: error.stack }),
        });
      }
    }
    
    module.exports = { errorHandling };
  • 相关阅读:
    阅读笔记第六次
    阅读笔记第五章
    阅读笔记第四章
    阅读笔记第三章
    软件需求分析课堂讨论
    阅读笔记第二篇
    阅读笔记五
    阅读笔记五
    阅读笔记三
    阅读笔记二
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13385949.html
Copyright © 2011-2022 走看看