Express js error handling

后端 未结 5 1601
无人及你
无人及你 2020-12-15 18:19

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 pr

5条回答
  •  有刺的猬
    2020-12-15 18:50

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

提交回复
热议问题