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 };
  • 相关阅读:
    CMMI的5个级别
    ubuntu下的烧录工具
    Git 安装配置
    使用 Git & Repo 下载代码
    Git 忽略文件
    Git rebase
    使用Git进行本地提交后,未上传提交,却不小心删除了本地提交或提交所在分支,怎么办?????
    Repo
    IOS关于UIViewController之间的切换
    PresentModalViewController
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13385949.html
Copyright © 2011-2022 走看看