How to handle code exceptions in node.js?

后端 未结 4 1211
眼角桃花
眼角桃花 2020-12-08 10:49

I went through the documentation of Express, and the part describing error handling is completely opaque to me.

I figured the app they\'re referring to

4条回答
  •  生来不讨喜
    2020-12-08 11:15

    You can use the default error handler that express uses, which is actually connect error handler.

    var app = require('express').createServer();
    
    app.get('/', function(req, res){
      throw new Error('Error thrown here!');
    });
    
    app.configure(function(){
        app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
    });
    
    app.listen(3000);
    

    Update For your code, you actually need to capture the error and pass it to express like this

    var express = require('express');
    var http = require('http');
    
    var app = express.createServer();
    
    app.get('/', function (req, res, next) {
      console.log("debug", "calling");
      var options = {
        host:'www.google.com',
        port:80,
        path:"/"
      };
      http.get(options,
        function (response) {
          response.on("data", function (chunk) {
            try {
              console.log("data: " + chunk);
              chunk.call(); // no such method; throws here
    
            }
            catch (err) {
              return next(err);
            }
          });
        }).on('error', function (e) {
          console.log("error connecting" + e.message);
        });
    });
    
    app.configure(function () {
      app.use(express.errorHandler({ dumpExceptions:true, showStack:true }));
    });
    
    app.listen(3000);
    

提交回复
热议问题