0

Is there any way to send error to frontend on mongoDb connection error.I had tried in a different different way but I didnt get a solution.

var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);  
    var store = new MongoDBStore(
          {
            uri: config.connectionString,
            collection: 'tbl_session'
          });


      // Catch errors
        store.on('error', function(error) {
              app.get('/',function(req,res){

              res.send('NOT Connected....')
            });
    });
Mohammad Raheem
  • 1,131
  • 1
  • 13
  • 23
  • Add more details like what all you tried. – Harshal Yeole Jun 05 '18 at 06:23
  • 1
    Where does `MongoDBStore()` come from? It is not part of any official driver. You need to be a lot more specific in the question. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Neil Lunn Jun 05 '18 at 06:31
  • You can either use web socket or have a heartbeat request from client at some time interval. below answer from me is using web sockets. – Sunil B N Jun 05 '18 at 07:10

1 Answers1

2

You can use web sockets to push this information to the UI.

const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('../..')(server);
const port = process.env.PORT || 3000;
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);  
    var store = new MongoDBStore(
          {
            uri: config.connectionString,
            collection: 'tbl_session'
          });


      // Catch errors
        store.on('error', function(error) {
              socket.emit('mongodb-failed', error)
            });
    });
server.listen(port, () => {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(path.join(__dirname, 'public')));

io.on('connection', (socket) => {
  // when socket emits 'mongodb-connection-failed', this listens and executes
  socket.on('mongodb-failed', (data) => {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('mongodb-connection-failed', {
        errorDetails: data
    });
  });
});

now at client side:

var socket = io();
socket.on('mongodb-connection-failed', () => {
    console.log('you have been disconnected');
   //do more whatever you want to.
});

This above example is using socket.io. You can use any web socket library, see more here

Sunil B N
  • 4,159
  • 1
  • 31
  • 52