0

When using the firebase node library, the real time database, a promise is returned, but what happens if an exception happens in my code in the .then() method? How could I make the code go to the .catch() method? Here is the code that I am trying to make go to the catch method.

admin.database().ref('/something/something').once('value').then(function(data: admin.database.DataSnapshot) { if(data.val() === null) { return new TypeError('invalid'); } }).catch(function(err) { console.log(err); }); 

2 Answers 2

2

When you hear about try and catch, the third word you need to think about is throw!

throw new TypeError('invalid') 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You could simplify your error handling an make you code more readable using async-await

async function asyncFunction() { try { const data: admin.database.DataSnapshot = await admin.database().ref('/something/something').once('value'); if(data.val() === null) { throw new TypeError('invalid'); } } catch (err) { console.log(err); } } 

5 Comments

Seeing var and async/await (es8) in the same function makes me smile. Use const/let (es6)
@GrégoryNEUT Yes, yes you are right, changed it to const :). But for async/await you don't have to wait until es8 for async-await if you use typescript :)
Oh that's right didn't saw that was about typescript! Nice catch
Your answer helped me clarify how to use async/await. Thank you!
Glad to help, I'm a big async await fan I want to see it used everywhere :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.