Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
How to avoid internal server error without using try catch clause in node js?

Server.js file

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

I have read to handle internal server error Do like that. I even tried that too but it won't run as I wanted

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: {}
  });
});

How to avoid that so that the server won't shot down ?

Tried that link too https://expressjs.com/en/guide/error-handling.html , http://code.runnable.com/UTlPPF-f2W1TAAEU/error-handling-with-express-for-node-js

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

For express middleware error handling

Catch 404 and forward to error handler

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

Catch the uncaught errors that weren't wrapped in a domain or try catch statement

Note: Do not use this in modules, but only in applications, as otherwise, we could have multiple of these bound

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

});

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

process.on('SIGINT', function() {
    process.exit(0);
});
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!