node.js - Global exception handling in Express
PHPz
PHPz 2017-05-16 13:35:30
0
2
1693

1. Is the following server configuration to capture routing exceptions correct?
server.js

const express = require("express");
const app = express();

// ...加载中间件


// ...配置路由

// 异常处理
// 如果是开发环境,则打印异常到控制台
if (app.get("env") === "development") {
  app.use((err, req, res, next) => {
    console.error("Error",err);
    next(err);
  });
}

// 如果是非开发环境,则向页面输出错误信息
app.use((err, req, res, next) => {
  res.status(err.status || 500);
  res.render("error", {
    message: err.message,
    error: {}
  });
});

app.listen(3000);

2. The following is a routing object. In the absence of promise (async/await), an exception will be thrown normally and captured in the server
xxxRouter.js

const router = require("express").Router();

router.all("/test/error", (req, res) => {
    throw new Error("我就是异常!!!");
});

But in the case of promise(async/await), an error will be reported in the console, and the capture in the server cannot be captured, resulting in q timeout

(node:30875) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: 我就是异常!!!
(node:30875) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

xxxRouter.js

const router = require("express").Router();

router.all("/test/error", async(req, res) => {
    throw new Error("我就是异常!!!");
});

3. In actual use, each route must try/catch and handle exceptions, which feels very redundant

// 冗余的router
router.all("/test1", async(req, res) => {
    try{
       // ...处理一些事务
       // ...各种 await
       res.end(
           // 成功返回内容
       );
    }catch(err){
        // 此处希望throw err 让server接收并处理,但是会报错
        res.end(
           // 失败返回内容
       );
    }
});
// ...之后还有很多router都要try/catch依次处理异常
=、=
PHPz
PHPz

学习是最好的投资!

reply all(2)
伊谢尔伦

The

async function returns a Promise 对象,这个函数中抛出的异常需要通过 Promise 对象的 catch()then() for the 2nd parameter to handle.

Of course, if you want the outer function to use await,就不是用 catch()then() 来处理了,而是像同步调用那样用 try ... catch ... for processing.

In my impression, Express itself does not support Promise/yield/async/await (I don’t know if the new version has developed related support). Nowadays, Koa, which has better support for Promise/yield/async/await, is generally used.

曾经蜡笔没有小新

process.on('unhandledRejection', processErrorHandler);

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template