Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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");
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
513 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...