I have an application in Node.js that whenever an error occurs it falls, having to be restarted manually, always. How do I get the error reported, but does the application continue to run?
I have an application in Node.js that whenever an error occurs it falls, having to be restarted manually, always. How do I get the error reported, but does the application continue to run?
To prevent your application from crashing with errors you can also use the try () and catch () methods, for example:
var exemploFunc = function(req, res) {
try {
console.log('Nenhum erro :)');
} catch(e) {
console.log('Ops, um erro ocorreu!');
}
};
One possibility to catch exceptions at a global level is to use
process.on('uncaughtException', function (err) {
console.log(err);
})
but is considered a bad practice because your program may be in an inconsistent state after the exception. It's an emergency patch!
Ideally, you should test your program to minimize bugs exceptions, and keep it running by using a script that reloads the node as soon as it exits. Exceptions that are not bugs should be captured "close" to where they occur, not at a global level.
You get reconnect by getting 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'll give you 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><scripttype="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>
Example site code: link