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'
Related
I am writing middleware code for setting up authentication and token validation in my nextjs app. I am using throw instead of returning value from the helper function.
But throw (last statement) is not working in the following code:
async function validate(request: NextRequest) {
const tokenid = "test";
if (tokenid) {
try {
// in case of error
throw new Error("test");
} catch (error) {
console.error("validate: ", error);
}
}
throw new Error("tokenId validation failed");
}
This function is called within another function and where the last statement is simply ignored.
export async function googleAuthValidate(request: NextRequest) {
let response = NextResponse.next();
try {
validate(request);
console.log("throw didnt go into catch");
} catch (error) {
console.error(error);
response = NextResponse.rewrite("/unauthorized");
} finally {
return response;
}
}
I have created a repository for this issue for easy reproduction: repo
I created a simple custom exception based on this link as follows:
function userErr(message) {
logger.info("reach user error function")
const error = new Error(message);
error.type = "userErr";
return error;
}
function failureErr(message) {
logger.info("reach failure error function")
const error = new Error(message);
error.type = "failureErr";
return error;
}
The expected behaviour is Express will throw this error to the custom error handler middleware at the end of the server.js file:
app.use((error, req, res, next) => {
console.log("Error Handling Middleware: " + error.message);
if (error.type === "userErr") {
res.status(400).json({
status: "error",
statusCode: "400",
message: error.message
});
} else if (error.type === "failureErr") {
res.status(500).json({
status: "fail",
statusCode: "500",
message: error.message
});
} else {
res.status(500).json({
status: "error",
statusCode: "500",
message: error.message
});
}
});
app.listen(8080, () => {
console.log("listening on 8080...");
}); //the server object listens on port 8080
When I put these functions above the routes (app.get, app.post, etc...) in the server.js file (this should be index.js for most people), it works fine. But when I start stripping out these routes and put them into a route file in the routes folder instead, the traffic does come to the route correctly, but whenever an error occurs and executes the function above, JavaScript threw an error at the 2nd line, which is:
const error = new Error(message);
for example:
const error = new Error(message);
^
Error: [object Object]
at new failureErr (file:///.../src/server.js:89:17)
at file:///.../src/routes/testRoutes.js:104:21 {
type: 'failureErr'
Which is weird! I have tried putting these functions into a separate file and importing them into the route file, but it still shows the same error.
I mimicked the folder into the codesandbox (I couldn't manage to make it run) so you can understand the context. The index.js by itself is the one that works, while index2.js with the routers folder is the one that failed.
Appreciate any feedback on the questions, or any ideas on where I did something wrong
The code you show in your sandbox is doing this throw new userError("It's an user error");, but userError() is not properly set up as a constructor and thus can't be called with new. This is the code in your sandbox:
app.get("/api/v1/test", (req, res, next) => {
try {
const userErr = req.headers.userErr;
console.log(userErr);
if (userErr === "true") {
throw new userError("It's an user error");
} else {
throw new failureError("It's an failure error");
}
} catch (e) {
next(e);
}
});
The code you show has not made either userError() or failureError() into classes or constructors. They are merely functions. Therefore, they can't be called with new.
If you want to make them into classes, then do something like this:
class userError extends Error {
constructor(message) {
super(message);
console.log("reach user error function");
this.type = "userErr";
}
}
Note, this is the more modern way of doing this than what is shown in the article you reference (which is apparently old).
Or, you can just use what you have as functions:
app.get("/api/v1/test", (req, res, next) => {
try {
const userErr = req.headers.userErr;
console.log(userErr);
if (userErr === "true") {
next(userError("It's an user error"));
return;
} else {
next(failureError("It's an failure error"));
return;
}
res.send("ok");
} catch (e) {
next(e);
}
});
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 ") }
}
}
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);
In my meteor project, I want to use generic functions in my Meteor.methods
(Mostly because I don't want users to call this functions from the client).
I'm defining this function in another file :
const ldapPing = (callback) => {
try {
ldapAuth.client = createClient({
url: Meteor.settings.private.LDAP.URL,
});
ldapAuth.client.on('error', () => {
throw new Meteor.Error('500', 'Cant join.');
});
callback(null, true);
} catch (exception) {
callback(exception, null);
}
};
And I'm calling it in my meteor methods like this :
'test.ldap': function testLdap() {
try {
const future = new Future();
ldapPing((error, result) => {
console.log('ERROR : ' + error);
console.log('RESULT : ' + result);
if (error) {
future.throw(error);
} else {
future.return(true);
}
});
return future.wait();
} catch (exception) {
throw exception;
}
},
However, the Meteor.error is not returned to the Meteor method and is immediatly throw from the simple function ldapPing, which stops meteor with "Exited with code: 1".
Any idea why ?
(This example is made for this question, ofc in this case there is no benefits to externalize this function)