I'm not sure why my function is not exiting after running. The code does not exit execution after resolving a promise.
I am using Firebase Admin SDK to send a message with the following:
var message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
admin.messaging().sendAll([message])
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
after printing to the console 'Successfully sent message:' the code console is still running and not return. What am I doing wrong?
For reference here is the signature of the firebase message send:
send(message: admin.messaging.Message, dryRun?: boolean): Promise<string>;
There might be something in the Firebase Admin SDK that is keeping the process from exiting. You can force the process to exit when you're done by simply adding process.exit(0) to the end of the then callback, if that's when you want it to terminate.
If you think this behavior is a bug, you can file it on the Firebase Admin SDK GitHub.
Related
I am attempting to make a connection to a MySQL database using Express and Mariadb. The IP for the database changes while I move the PI that it is connected to from the office to my Home. If I don't change the IP before hand then it obviously can not connect to the database, this is fine and a known issue but I want to be able to handle this error without having Node throw a fatal error and shut down
app.get("/db", (req, res) => {
console.log("ping to db!")
MariaPool.getConnection()
.then((conn) => {
conn.query("SELECT * FROM devTable")
.then((data) => {
console.log(data)
res.json(data)
})
.catch((error) => {
console.log("Poor SQL format")
})
.finally(() => {
conn.end()
})
})
.catch((error) => {
console.log("No connection")
res.json({
err: error
})
})
});
Above I attempt to make a connection to the Database, when the IP is wrong it goes to the catch block and logs No Connection as it should, however afterwards a second fatal error is thrown
text: 'Connection timeout: failed to create socket after 1002ms',
sql: null,
fatal: true,
errno: 45012,
sqlState: '08S01',
code: 'ER_CONNECTION_TIMEOUT'
this causes the Node server to shutdown. Try as I may I am unable to find a way to handle this error.
My initial thought is to somehow stop the attempts to make the socket creation once it goes into the catch block but I'm not sure if that is possible.
I've taken a look at This Question but app.use does not solve my problem
Tried the implementation of my own Promise as documented in this question and it still does not handle the fatal error
To sum it up, is it possible to handle fatal errors such as this to allow the program to continue?
I'm building Node & React application and I'm working on authentication now. For example when someone will type e-mail that already exist in database, I would like to send a response with error with proper status and message that email already exist.
I'm already done with sending errors when it's needed. Problem is that even if I pass error message within, I can not display it on frontend.
back-end (Node):
User.find({ email: email })
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: 'Mail exists' // <-- I want to pass message here
})
}
front-end (React):
axios.post('http://localhost:3000/user/signup', newUser)
.then(response=> {
dispatch({
type: actionTypes.SIGNUP_SUCCESS
})
localStorage.setItem('JWT_TOKEN', response.data.token)
axios.defaults.headers.common['Authorization'] = response.data.token
})
.catch((err)=> {
console.log(err.message) // <-- I want to display message here
})
My actual result is that i see Request failed with status code 409 in my console.
Therefore I would like to see Mail exists.
Thank You for help :)
Best regards.
// you can try below code in your catch block
.catch((err)=> {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if (err.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
})
I agree with Mohammed, you can find error message under data property.
console.log(error.response.data.message);
I can't seem to figure out any reason why a service worker would be deleted with the code that I have that registers or actually is the service worker.
But in this site, it shows up as deleted in the Service Workers section of the chrome dev tools (image below).
Yet it is also registering properly as logged in the console (same image below).
Here is the service worker registration code:
if('serviceWorker' in navigator){
navigator.serviceWorker.register('/earnie.min.js', { scope: '/'}).then(function(registration){
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(error){
console.log('Service worker registration failed, error:', error);
});
}
Here is the service worker code:
var cachename="e2",cachelist=";;.;/;./;/privacyPolicy.html;/css/main.css;/css/normalize.css;".split(";");
self.addEventListener("install",function(a){
a.waitUntil(caches.open(cachename).then(function(a){
return a.addAll(cachelist)
}))
});
self.addEventListener("fetch",function(a){
a.respondWith(caches.match(a.request).then(function(b){
return b?b:fetch(a.request.clone(), { credentials: 'include', redirect: 'follow' })
}))
});
What is causing it to be deleted and not registering?
Registration succeeded, but installation actually fails. Your waitUntil() promise is not resolving, which causes InstallEvent event to fail, thus deleting the ServiceWorker. cachelist probably returns invalid/empty values when you run split(';')
I recommend ensuring that cachelist is an array with valid URI values, then you can debug within the install event**
self.addEventListener("install", event => {
event.waitUntil(
caches.open(cachename)
.then(cache => cache.addAll(cachelist))
.catch(error => console.error('💩', error))
)
})
**You'll most likely need "Preserve log" console option enabled in Chrome Dev Tools to see the console error.
I'm trying to make an alert window saying there's an error, When trying to post a message offline. But the catch doesn't seem to ever work, Maybe it just works in other cases?
here's my code :
return (dispatch) => {
dispatch({
type: POST_TO_DB,
});
firebase.database().ref(locationInDB).push(object)
.then((data) => {
dispatch({
type: POST_TRADE_TO_DB_SUCCESS,
}); // success
})
.catch((err) => {
console.log("failed to post...")
dispatch({
type: POST_TRADE_TO_DB_FAILED,
}); // failed
});
};
Is there an alternative? Or am I doing something wrong?
When there is no network connection, the Firebase client will keep the pending write in memory until the network connection is restored, at which point it will complete the write.
The catch() clause is triggered if the write fails on the server, not when it can't complete.
Also see:
To detect if the client is connected to the Firebase backend, see Detect if Firebase connection is lost/regained
Firebase synchronisation of locally-modified data: handling errors & global status
This problem annoys me, because I know it has something to do with me not understanding the issue properly - which makes it really hard to track down answers for, despite spending hours reading and trying different things.
My question/problem is this, I am saving a user to a mongodb database when they signup, my schema doesn't allow for duplicate emails, and sends me back an error. I am able to console log the error in the terminal, but I am having problems sending it back to the client. Or I'm having a problem doing something with it, if it comes back, I'm not too sure where in those two steps I am losing access to the error message.
Here is my POST route for saving the user:
router.post('/users', (req, res) => {
let body = _.pick(req.body, ['email', 'password']);
let user = new User(body);
user.save().then(() => { // this all works and will save the user, if there are no errors
return user.generateAuthToken();
}).then((token) => {
res.header('Authorization', `Bearer ${token}`).send(user);
}).catch((err) => { // This is where my problem is
console.log(err); // This will log the mongodb error here, about duplicate emails
res.status(500).send(err); // I'm trying to send the mongodb error message back to the client to display it on the screen (I will handle making the message friendly to read, once I can get this to work)
});
});
So my catch is getting the mongo error, and then I try to respond with it, by sending it to the client.
Here is my client side code:
axios({
method: 'post',
url: '/auth/users',
headers: {
'Content-Type': 'application/json'
},
data: {
email,
password
}
}).then((res) => {
console.log('this is the response', res);
if (res.status === 200) {
var authToken = res.headers.authorization.split(' ')[1];
authenticateUser(authToken);
this.props.history.replace('/dashboard');
} // This all works fine for a signup with no errors
}).catch((err) => {
console.log('Signup error:', err);
// I am expecting the above line of code to log the long Mongodb
// error message that I am sending back in my res.status(500).send(err)
// catch call from the server, but instead all I am getting is
// "Signup error: Error: Request failed with status code 500"
});
Either I'm not sending the error correctly, or I'm not handling it correctly when it comes back, but I have no idea which it is or why.
I can't even send back res.status(500).send('some string here') and access that string.
Thanks
Update
So I just checked in postman, by sending a POST that could cause the error, and I am getting the correct response sent through.
My server catch actually looks like this:
.catch((err) => {
res.status(500).send({message: err.message});
});
And the postman response body looks like this:
{
"message": "E11000 duplicate key error collection: authBoilerplate.users index: email_1 dup key: { : \"email#example.com\" }"
}
So I'm just not handling it correctly in my client side code, still at a loss though.
Thanks everyone, I was able to find the answer to my question, so I'm posting it here in the hope that it might help someone else.
I was definitely sending my custom error message back, I just wasn't handling it properly on the client side.
When I was using a catch call on the client and logging the error, I was expecting to see everything included in the error. It turns out that the error comes back with a response property error.response, and that is where all the messaging is.
So changing my catch call to this:
axios(//... send post in here)
.then(// ... same as in my question)
.catch((err) => {
console.log('error', err);
console.log('error response', err.response); // this is where the actual error response message is error.response.message
});
resulted in logging the stack trace and the error response:
error Error: Request failed with status code 500
at createError (eval at <anonymous> (bundle.js:541), <anonymous>:16:15)
at settle (eval at <anonymous> (bundle.js:847), <anonymous>:18:12)
at XMLHttpRequest.handleLoad (eval at <anonymous> (bundle.js:520), <anonymous>:77:7)
error response Object {data: Object, status: 500, statusText: "Internal Server Error", headers: Object, config: Object…}
I was still expecting to be able to see that I had access to that 'response' property by logging just the error, so if anyone has any insight into that, it would be great to include in the comments.
Another way of solving this is by converting the error to string.
.catch((err) => {
res.status(500).send(err.toString());
});