执行js错误处理 [英] Express js error handling

查看:108
本文介绍了执行js错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用快递运行错误处理,而不是看到错误!!!的响应。就像我期望我在控制台上看到一些例外,然后进程被杀死。是这样的错误处理应该是设置,如果还有另一种方法来捕获错误?

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?

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");
});


推荐答案

有关错误处理的示例应用/指南可在
https://expressjs.com/en/guide/error-handling。 html
但是应该修复你的代码:

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

// 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");
});

这篇关于执行js错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆