如何在节点js中不使用try catch子句时避免内部服务器错误?

时间:2017-04-26 10:35:47

标签: node.js express error-handling routes internal-server-error

Server.js文件

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();
var os = require('os');
//app.use(logger('dev'));
app.use(bodyParser.json());

app.all('/*', function (req, res, next) {
    // CORS headers
    res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    // Set custom headers for CORS
    res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
    if (req.method == 'OPTIONS') {
        res.status(200).end();
    } else {
        next();
    }
});

// Auth Middleware - This will check if the token is valid
// Only the requests that start with /api/v1/* will be checked for the token.
// Any URL's that do not follow the below pattern should be avoided unless you
// are sure that authentication is not needed
//app.all('/api/v1/*', [require('./middlewares/validateRequest')]);
app.use('/', require('./routes')); // Write url in the routes.js file

app.use(function (err, req, res, next) {
    if (!err) {
        return next();
    }
    else {

            return next();

    }
});


//404 error handler


// If no route is matched by now, it must be a 404
app.use(function (req, res, next) {
    var err = new Error('URL Not Found');
    err.status = 404;
    var date = new Date();
    next(err);
});


// Start the server
app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + server.address().port);
});

我已阅读处理内部服务器错误 这样做。我甚至尝试过,但它不会像我想的那样运行

if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    console.log(err.message+'           w');
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

如何避免这种情况,以免服务器崩溃?

也尝试了该链接https://expressjs.com/en/guide/error-handling.htmlhttp://code.runnable.com/UTlPPF-f2W1TAAEU/error-handling-with-express-for-node-js

1 个答案:

答案 0 :(得分:0)

用于快速中间件错误处理

捕获404并转发到错误处理程序

app.use(function(req, res) {
    res.status(404).send({
        error: 'Not found'
    });
});

if (app.get('env') === 'development') {
    app.use(function(error, req, res, next) {
        debug('http_status: %d, %s', error.status || 500, error.message);
        next(error);
    });
}

app.use(function(error, req, res) {
    res.status(error.status || 500).send({
        error: 'Internal server error'
    });
});

捕获未包含在域中的未捕获错误或尝试捕获语句

注意:不要在模块中使用它,而只能在应用程序中使用它,否则,我们可能会有多个绑定

process.on('exit', function(code) {

});

process.on('uncaughtException', function(err) {
   console.log(err)
});

process.on('SIGINT', function() {
    process.exit(0);
});