node.js Express js 错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15684130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:02:37  来源:igfitidea点击:

Express js error handling

node.jsexpress

提问by Eric Speelman

I'm trying to get error handling running with express but instead of seeing a response of "error!!!" like I expect I see "some exception" on the console and then the process is killed. Is this how error handing is supposed to be setup and if so is there another way to catch errors?

我正在尝试使用 express 运行错误处理,但没有看到“错误!!!”的响应 就像我期望的那样,我在控制台上看到“一些异常”,然后进程被终止。这是应该如何设置错误处理,如果是这样,是否有另一种方法来捕获错误?

var express = require('express');
var app = express();

app.use(function(err, req, res, next) {
    console.log("error!!!");
    res.send("error!!!");
});

app.get('/', function(request, response) {
    throw "some exception";
    response.send('Hello World!');
});

app.listen(5000, function() {
  console.log("Listening on 5000");
});

回答by Ben Evans

An example app/guide on error handling is available at https://expressjs.com/en/guide/error-handling.htmlHowever should fix your code:

https://expressjs.com/en/guide/error-handling.html提供了一个关于错误处理的示例应用程序/指南, 但是应该修复您的代码:

// Require Dependencies
var express = require('express');
var app = express();

// Middleware
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the next middleware (your error reporter)
app.use(function(err, req, res, next) {
    if(!err) return next(); // you also need this line
    console.log("error!!!");
    res.send("error!!!");
});

// Routes
app.get('/', function(request, response) {
    throw "some exception";
    response.send('Hello World!');
});

// Listen
app.listen(5000, function() {
  console.log("Listening on 5000");
});

回答by Eric Elliott

A few tips:

一些提示:

1) Your code wasn't working because your error handler middleware was run before your route was reached, so the error handler never had a chance to have the error passed to it. This style is known as continuation passing. Put your error handler last in the middleware stack.

1)您的代码无法正常工作,因为您的错误处理程序中间件在到达您的路由之前运行,因此错误处理程序从来没有机会将错误传递给它。这种风格被称为延续传递。将您的错误处理程序放在中间件堆栈的最后。

2) You should shut down the server when you have an unhandled error. The best way to do that is to call server.close(), where server is the result of doing var server = http.createServer(app);

2) 当您遇到未处理的错误时,您应该关闭服务器。最好的方法是调用server.close(),其中 server 是这样做的结果var server = http.createServer(app);

Which means, you should do something like this:

这意味着,你应该做这样的事情:

var server = http.createServer(app);

app.use(function(err, req, res, next) {
  console.log("error!!!");
  res.send("error!!!");
  server.close();
});

You should probably also time out the server.close(), in case it can't complete (your app is in an undefined state, after all):

您可能还应该让 server.close() 超时,以防它无法完成(毕竟您的应用程序处于未定义状态):

var server = http.createServer(app);

app.use(function(err, req, res, next) {
  console.log("error!!!");
  res.send("error!!!");

  server.close();

  setTimeout(function () {
    process.exit(1);
  }, 3*1000);
});

I made a library that does all this for you, and lets you define custom responses, including specialized error views, static files to serve, etc...:

我创建了一个库来为您完成所有这些工作,并允许您定义自定义响应,包括专门的错误视图、要提供的静态文件等...:

https://github.com/ericelliott/express-error-handler

https://github.com/ericelliott/express-error-handler

回答by innay

I had the same problem and couldn't figure out what was wrong. The thing is if you have the express errorHandler defined then your custom error handler is never being called. If you have the next code, simply remove it:

我遇到了同样的问题,无法弄清楚出了什么问题。问题是,如果您定义了明确的 errorHandler,则永远不会调用您的自定义错误处理程序。如果您有下一个代码,只需将其删除:

if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

Worked for me:)

对我来说有效:)

回答by Anubhav Singh

Installing express install connect-domain, then something like this:

安装 express install connect-domain,然后是这样的:

var express = require("express"),  
    connectDomain = require("connect-domain"),
    app = express(),
    errorHandler;

// Our error handler

// 我们的错误处理程序

app.use(connectDomain());  
    errorHandler = function (err, req, res, next) {  
        res.send(500, {
           "status": "error",
           "message": err.message
        });
    console.log(err);
};

Then when setting up your endpoints, tack errorHandler on the end in a use():

然后在设置端点时,在 use() 的末尾添加 errorHandler:

app.get("/some/data", function (req, res) {  
    // ... do some stuff ...
    res.send(200, "Yay! Happy Success!");
}).use(errorHandler);

回答by Dominic

Create an error function:

创建误差函数:

function throwError(status, code, message) {
  const error = new Error(message);
  error.name = '';
  error.status = status;
  error.code = code;
  throw error;
}

e.g.

例如

throwError(422, 'InvalidEmail', '`email` should be a valid email address')

We assign nameto ''so that when we toStringthe error it doesn't prepend it with "Error: "

我们分配name''这样,当我们toString出现错误时,它不会在它前面加上"Error: "

As mentioned if you're using express you can create a special error handling middleware by specifying 4 arguments:

如前所述,如果您使用 express,您可以通过指定 4 个参数来创建一个特殊的错误处理中间件:

app.use((err, req, res, next) => {
  if (err) {
    res.status(err.status || 500).json({ code: err.code || 'Error', message: err.toString() });
  }
});

If you're not using express or otherwise prefer, add that code to your catchhandler instead.

如果您不使用 express 或以其他方式更喜欢,请将该代码添加到您的catch处理程序中。

Why?

为什么?

  1. Modern apps handle JSON, throwing errors in JSON makes more sense and results in cleaner UI code.

  2. You should not only throw error messages because they are imprecise to parse. What if the UI is a multilingual app? In that case they can use the codeto show a localized message.

  1. 现代应用程序处理 JSON,在 JSON 中抛出错误更有意义,并产生更清晰的 UI 代码。

  2. 您不仅应该抛出错误消息,因为它们解析不精确。如果 UI 是多语言应用程序怎么办?在这种情况下,他们可以使用code来显示本地化消息。