Node.js application always falls after an error

Asked

Viewed 749 times

1

I have an application in Node.js that whenever any error occurs it falls, having to be restarted manually, always. How do I make the error report, but the application keeps running?

  • 1

    What error is displayed? It is probably more valid to try to fix the error than to restart Nodejs. Post more details. In any case, to restart the Nodejs, it would be necessary.

  • Thanks for the reply, Vinicius. I solved as you said, I fixed the function that was giving the error. It was just

  • 1

    Thank you for the answer, Vinicius. I solved as you said, fixed the function that was giving the error. It was just putting a callback that was in the wrong place. Vlw

3 answers

2

To prevent your application crashing with errors you can also use the Try() and catch() methods, example:

var exemploFunc = function(req, res) {
    try {
      console.log('Nenhum erro :)');
    } catch(e) {
      console.log('Ops, um erro ocorreu!');
    }
};

1

One possibility to capture exceptions on a global level is to use

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

but it is considered a bad practice because your program may be in an inconsistent state after the exception. It is an emergency patch!

The ideal is to test your program well to reduce as much as possible exceptions due to bugs, and keep it running using a script that reloads the Node as soon as it leaves. Exceptions that are not bugs should be captured "near" where they happen, not at a global level.

0

Parameter Reconnect receiving true when opening the connection.

io.connect(                                                                 // CRIAR UM SOCKET
            $("#socket").val(),{                                            // ENDERECO DO SOCKET
            'reconnect': true                                               // que irá informar se o socket irá tentar se conectar caso perca a conexão com o Server.
           ,'reconnection delay': 500                                       // informa o tempo em milissegundos que será o delay da tentativa de conexão.
           ,'max reconnection attempts': 1000                               // informa o valor máximo de tentativas de conexão com o Server.
           ,'secure': false                                                 // informando se a conexão com o Server irá utilizar criptografia (conexões HTTPS).
    });

I will pass a more complete example below:

    <!DOCTYPE html>
<html>
<head>
    <title>Exemplo utilizando socket.io</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <!-- CSS -->
    <style type="text/css">
        h2 { 
            color: #439;
            font-size: 120%;
        }
    </style>

    <!-- JS -->
    <script type="text/javascript" src="http://localhost:8088/socket.io/socket.io.js"></script> 
    <script type="text/javascript">
        // Criando a conexão com o Socket.io
        var socket = io.connect('http://localhost:8088',{
             'reconnect': true
            ,'reconnection delay': 500
            ,'max reconnection attempts': 1000
            ,'secure': false
        });

        // Emitindo o evento para o Server
        socket.emit('userconected');

        // Listeners

        /**
         * Monitorando o evento "showmessage" que será disparado pelo Server
         * @param {String} msg Mensagem a ser exibida
         */
        socket.on('showmessage', function(msg){
            var messageEl = document.getElementById('message-info');

            // Exibindo a mensagem enviada
            messageEl.innerHTML += msg;
        });
    </script>
</head>
<body>
    <h2>Mensagens do socket.io</h2>
    <div id="message-info"></div>
</body>
</html>

Sample code of the site: http://wessdevel.blogspot.com.br/2012/08/instalando-e-configurando-nodejs-e.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.