catch never outputs the console even though I know it's failing - node.js

I have my mongodb service stopped, so I know that my front end is not connected to my DB. I am using react and express.
Upon my app starting, I want to indicate that to the user somehow the server is offline so I figured if my original get call for users fails, then the server is offline.
I'm doing a simple call:
componentDidMount () {
axios.get ('/api/users')
.then ((res) => this.setState(
{ users : res.data }
))
.catch ((error) => {
//console.error(error);
console.log('error found : offline');
});
}
But nothing happens in situation. I never get the catch call for the console. Am I going about this wrong? I'm new to backend so this is all a learning experience for me.
I was going to set a failed flag and then render a display error for the user and then retry the connection every 1500ms or something (is that bad programming?).

Related

How to show the error alerts on UI whenever the catch error or console error comes and the server stops in localhost or in production side (heroku)?

I want a solution for how I can write the code in nodejs so that whenever console error occurs I want to send the alert erros on UI sid to the user so that he can go back or refresh or login again instead of blocking the page/ website in between whenever the application error logs comes in heroku.
Please provide me a solution for this!!!
Thanks!
Edit:
I am asking for general only. Means just like I was testing my web app on heroku after making live and in between while testing an error occured and I got redirected to the heroku application error log page like this below. So I just want to ignore this and instead of this an alert should appear telling the user to go back or login again as some error occured. but not to break the page in between like this.
:(
The server can't send the response to the client if it crashes completely. When a server crashes it means that your code is not handling the error properly.
As you didn't specify which programming language or framework you are using. I assume that it is Node.js as you mentioned .catch()
In this case, you should have a try/catch block in your code or a .catch if you are using promises. The error occurred but the server won't just crash completly.
You will need to have something similar as below in your route handlers:
Async/Await:
try{
// Do stuff
}catch(err){ // Bad things happen
// Log the error so you know what went wrong
console.log(err)
// Send the error response to the frontend
res.status(500).json({msg:'Server Error'})
}
Promises:
something
.then(//Do stuff)
.catch(err => { // Bad things happened
console.log(err)
// Send the error response to the frontend
res.status(500).json({msg:'Server Error'})
})

"sorry, too many clients already" error raised with PostgreSQL (w/ TimescaleDB extension) pool and nodeJS

I have a nodeJS application that extensively interacts with the database (PostgreSQL w/ TimescaleDB extension) and I have trouble with the "sorry, too many clients already" error being raised despite using a Pool.
I am 99% sure that clients are released when needed and even if they are not, newly created ones should wait forever instead of throwing an error.
Methods that interact with the database are constructed this way:
return this.timescalePool.connect()
.then((timescaleClient) => timescaleClient.query(“myQuery”)
.then((res) => {
timescaleClient.release();
// code
})
.catch((err) => {
try {
// Avoid throwing an error when the client has already been released.
timescaleClient.release() ;
} catch (err) {}
// code
})
The current configuration for the postgres max_connection is 250 and 75 for the pool size.
What could be the reasons of having the "too many clients" error despite using a pool ?
What is the best option for live monitoring the behaviour of the pool / clients and have a better understanding of what is happening ?

Nodejs set timeout for Redis requests

I've written a simple service using redis to store data in memory or fetch from disc and then store in memory and want to set a timeout for slow requests. I'm hoping to find a way make a get request with a timeout to prevent this a request from hanging. Any help is appreciated.
So, there are a few things you can do here. But, first I wonder if you are attempting premature optimization. Redis in most normal situations is blazingly fast, and if you are finding performance issues on the client, then that indicates that you have some issues with your data or how you are processing it in redis. This should be fixed this in redis, there is nothing you should do in your client to handle slow requests.
So, if you are seeing occasional slowdowns, what are they coming from? This is not a normal redis issue, and should be addressed instead of looking for a javascript fix.
If you are still looking for a javascript fix, you could do something like this:
const client = require('redis').createClient(...);
export async function asyncSetEx(key) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error('Timed out'));
});
client.setEx(key, (res, err) => {
if (err) {
reject(err);
} else {
resolve(res);
}
clearTimeout(timer);
});
});
}
Though, I'd recommend generalizing this so that it works for any redis function with any number of parameters.
prevent this a request from hanging
If you set enable_offline_queue to false, all Redis commands will throw an exception immediately instead of waiting to reconnect. You can then catch that exception and do your fetching from disc or some DB.
Couldnt find anything in the documentation regarding this and found many such questions here on SO, hence posting in this old question.
Do keep in mind that, with enable_offline_queue set to false, the commands that you issue while there's some connection issue with the server will never be executed.

Reponse Failed in nodejs. How to handle properly

Cases:
When i insert the data in database through nodejs service. Data Insert successfully in Database(like mysql)
But response failed(for example client call insert service data successfully stored in database. but response failed for network problem anything, client don't know data inserted or not)
So How to handle above case properly?
Your question is bit wide for answer , but still I think , this is might be what you are looking for
model.User.create({your_data})
.then(user => { // if all goes right the this block will be executed
}).catch(err => { // if anything goes wrong this block will be executed
console.log(err);
// from here you can send err in response OR redirect to error page
})

Meteor - How to handle external API connection errors?

I'm using a few external API's (some in timers, every minute or so) and sometimes I get some connection errors because of network problems or because the external systems are down for some reason. When I get this errors, the app restarts, and if the error persists the app continues restarting.
Any ideas on how can I ignore the connection error and keep the app running?
Code Example:
try {
var req = https.request(options, callback);
req.write(JSON.stringify(params));
req.end();
} catch (e) {
throw e;
}
Based on your code example. You're doing throw e inside your try catch. Essentially, you're catching an error and then throwing the error. Just do console.error(err) or however you want to handle that error, without throwing. This is what will cause your instance to stop.

Resources