Not able to catch error for .on() in firebase - javascript

I am using below code to retrieve a value
try {
discountFbRef.orderByChild('discode').equalTo(code).on("value", function(snapshot) {
console.log('snapshot val discode', snapshot.val().discode);
if (snapshot.exists()) {
snapshot.forEach(function(data) {
$scope.discountApplicable.id = data.val().id;
});
} else {
console.log('It doesnt exist');
}
}, function(error) {
console.log(error);
});
} catch (error) {
console.log('error occured during search', error);
}
When there is value equal to the search string it's working fine. But when I try to find a keyword that doesn't exist in "discode", It throws
Uncaught TypeError: Cannot read property 'discode' of null
For some reason even though I try to catch the error with try-catch and error function I am not able to catch it.
I need a way to handle the error and show message that search string doesn't exist.

So, the functions that are passed to the second and third parameters of .on are called a callback functions. That means they might get called after (asynchronously) the code you've posted has executed. You'll want to move your try-catch inside of the callback function.
function handleValueSuccess(snapshot) {
try {
console.log('snapshot val discode', snapshot.val().discode);
if (snapshot.exists()) {
snapshot.forEach(function(data) {
$scope.discountApplicable.id = data.val().id;
});
} else {
console.log("It doesn't exist");
}
} catch (error) {
console.log('error occurred during search', error);
}
}
function handleValueError(error) {
console.log('error occurred on value', error);
}
discountFbRef
.orderByChild('discode')
.equalTo(code)
.on("value", handleValueSuccess, handleValueError);

Related

cannot catch Meteor.Error in client when error thrown from server side of meteor method

I have a meteor call and meteor method. When I throw Meteor error then it is not caught inside meteor call's error but instead in response
Here is my meteor method
Meteor.call("updateFtIndex", id, $(`#idx-${id}`).val(), function (error, result) {
if (error) {
console.log('error: ', error.reason);
}
else {
console.log('result', result);
}
})
and here is my meteor method
Meteor.methods({
updateFtIndex: function (_id, index) {
try {
let isIndexExists = Meteor.users.findOne({_id, "profile.featuredProviderIndex": index }, {fields:
{"profile.featuredProviderIndex": 1}});
if(isIndexExists){
console.log('isIndexExists: ', isIndexExists);
throw new Meteor.Error( 400, "Sorted index already exist !!!");
}
else {
console.log("else");
return Meteor.users.update({_id}, { $set: { "profile.featuredProviderIndex": index } });
}
} catch (error) {
return error
}
}
})
And I get the thrown error inside result of meteor call
Can somebody tell me what is wrong with the code ?
You are catching the throw and your catch is returning the error but the better way to return an error to the front is your change it to this:
try {
let isIndexExists = Meteor.users.findOne({_id, "profile.featuredProviderIndex": index }, {fields: {"profile.featuredProviderIndex": 1}});
if(isIndexExists){
console.log('isIndexExists: ', isIndexExists);
throw new Meteor.Error( 400, "Sorted index already exist !!!");
}
else {
console.log("else");
return Meteor.users.update({_id}, { $set: { "profile.featuredProviderIndex": index } });
}
} catch (e) {
throw new Meteor.Error(400, e.toString());
}
You are returning error instead of throwing it from catch block.

will `return` be caught on error in a try/catch block?

I have a try/catch block within which I run my synchronous function call, I wonder why it won't be caught by the catch if the function return an Error. In this case I have a known issue in mySyncFunction and I don't want to throw on that, because I want the test function to catch that
function test() {
try {
return mySyncFunction();
} catch (error) {
console.error('my error message', error);
return [];
}
}
function mySyncFunction() {
try {
// Do stuff
const expectedIssue = true;
if (expectedIssue) {
return Error('the known issue happended');
}
} catch (e) {
throw Error(e)
}
}
console.log(test());
If there is no error occuring during the call of this.mySyncFunction(args) it will returns normally. However, if there is an exception raised during this call, it will simply go directly to the catch, console.error your error and return [].
You're not throwing an Error, you're returning one. Errors and other exception are only caught when you throw them, not by simply being around.
The correct way to actually see the exception being caught is
function test() {
try {
return mySyncFunction();
} catch (error) {
console.error('my error message', error.message); // notice error.message
return [];
}
}
function mySyncFunction() {
throw new Error('my error'); // notice throw
}
console.log(test());

Why Method call inside onSubmit throws error?

I try to call metetor method but it is throwing me error "Uncaught TypeError: Meteor.call is not a function" but when I try to call same in another file inside imports/api/some.js this works, meaning the call code is correct but it is working inside onSubmit why ? Here is github url
File : imports/ui/otp.js
onSubmit(e) {
e.preventDefault();
let otp = this.refs.otp.value.trim();
Meteor.call('find-otp', otp, (error, result) => {
if(error) {
console.log('otp error check', error);
} else {
console.log('otp res check', result);
}
});
}
File : imports/api/db.js
Meteor.methods({
'find-otp' (otp) {
// if(!this.userId) {
// throw new Meteor.Error('not-authorized');
// }
console.log('otpcheck', otp);
return true;
// return otp; // also I try this
}
});
Make sure you properly import Meteor:
import { Meteor } from 'meteor/meteor'

how to display http error message angular 6

I am using the below methods to send data. I want to display an error response on my component. How can I console log error message in my component?
component.ts
signup(){
return this.loginservice.signupUser(this.model).subscribe(data => {
console.log(data.error);
});
}
service ts
signupUser(signupuserModel: any = {}):Observable<any>{
return this.http.post(`${this.signuouserurl}`,signupuserModel)
}
error message
In RxJS, subscribe() method can have 3 functions
next() if observable emits value.
error() if there's an error thrown from the Observable
complete() if the observable is completed.
What you need to do is to add an extra arrow function in your server call inside subscribe() method
public error: any;
signup() {
return this.loginservice.signupUser(this.model).subscribe(success => {
console.log(success);
}, error => { // second parameter is to listen for error
console.log(error);
this.error = error;
});
}
If you want to show the error in your component.html, you can use the interpolation {{ }}
component.html
<div class="error">{{ error }}</div>
try
signup() {
return this.loginservice.signupUser(this.model).subscribe(data => {
console.log(data);
}, err => {
console.log(err);
});
}
You can also use try-catch approach in following way
async signup() {
try {
let data = await this.loginservice.signupUser(this.model).toPromise();
console.log(data)
} catch (e) {
console.log(e);
}
}
However not all http codes raise exception
you can choose any method to display an error.. on of the best way is seprate the success and error response with following code (for this your http call must thrown an exception if not then you have to chose the second option )
signup() {
return this.loginservice.signupUser(this.model).subscribe(success => {
console.log(success);
}, error => {
console.log(error);
});
}
or you can write conditional code like
signup() {
return this.loginservice.signupUser(this.model).subscribe(success => {
console.log(data);
if(success.status == 406){ console.log("success")}
else { console.log("Error ") }
}
}

How To Catch Errors When Adding a Field With Knex.JS

We're using knex.js to generate and execute SQL. We're having trouble trapping errors when adding fields to an existing table and the documentation does not cover this specific use-case. Attempting to add a duplicate field does return an error in the console (VSCODE), but none of standard events are called on an error so we can't trap it in code. Here's the code:
knex.schema.table(tableName, function(table) {
table.string('test').catch(function(e) {
callback(e)
});
}).then(function(e) {
callback(e);
}).catch(function(e) {
callback(e);
})
This is returned in the VSCODE console:
{ [TypeError: table.string(...).catch is not a function] 'error#context': { accessToken: undefined } }
However, none of the callbacks are called. How can we check for errors when adding fields?
UPDATE #1 This code will call the callback, but obviously without any error information. And, the same error appears in the console regardless:
table.string('test').catch(
callback(null, Lib.returnEvent(false))
);
UPDATE #2 No callbacks are called with the following code:
knex.schema.table(tableName, function(table) {
table.string('ddd');
}).then(function(e) {
callback(e);
}).catch(function(e) {
callback(e);
})
UPDATE #3 In this example the first callback is called, but the function hangs on subsequent calls:
knex.schema.table(tableName, function(table) {
table.string('ddd');
callback(true);
}).then(function(e) {
callback(true, e);
}).catch(function(e) {
callback(false, e);
})
I was able to resolve this issue by switching to the Knex callback approach rather than using the promises approach. This code works consistently:
knex.schema.table(tableName, function(table) {
table.string(tableFieldname);
}).asCallback(function(err) {
if (err) {
callback(false, err);
} else {
callback(true);
}
})
This works for me
return knex('users')
.insert({
username: req.body.username,
password: hash,
})
.returning('*')
.bind(console)
.then(console.log)
.catch(console.error);

Categories