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 };
  • 相关阅读:
    js 类型检测
    js笔记
    js 笔记 -- 随机生成颜色值
    js笔记 -- toString() 和String()
    jquery 实现的josnp
    json 、jsonp
    关于js 中的 this
    [LeetCode][JavaScript]Symmetric Tree
    [LeetCode][JavaScript]Balanced Binary Tree
    [LeetCode][JavaScript]Wiggle Sort II
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13385949.html
Copyright © 2011-2022 走看看