Error when setting context... Cannot read property 'input' of undefined' - dialogflow-es

The error is:
TypeError: Cannot read property 'input' of undefined'
I am setting the context like so:
conv.contexts.set('pgnotes',1000,
{ 'pg':pgContext.pg,
'notes':response,
'lastReferencedPage':-1
}
);
I have set contexts using the same general code successfully in other areas. I'm not sure why it's an error here.
I'v submitted the question to actions on google support but I don't expect them to respond. Hoping someone here can offer an idea!
Some surrounding code
APIGetNotes(pgContext.pg, uniqname).then(
response=>{
console.log("conv.contexts %O", conv.contexts);
console.log("pgContext.pg: "+pgContext.pg);
console.log("notes: %O",response);
console.log("About to set context");
conv.contexts.set('pgnotes',1000,
{ 'pg':pgContext.pg,
'notes':response,
'lastReferencedPage':-1
}
);
respondBrowseNote(conv);
}
).catch(
error=>{
console.log("ERROR getting notes for pg '"+pgContext.pg+"' Error:'"+error+"'");
conv.ask("There was an error getting notes, try again later");
}
)

Related

Firestore Transaction Error Appears as Empty Object

When I run a transaction inside a try {} catch(error){} block in Firestore, I noticed that when I try to store the error in logs, it appears as empty object. However, when I print it into console in the emulator, I get a proper error message.
Example code:
try {
await admin.firestore().runTransaction(async (t) => {
t.set(myRef, myNewData)
})
} catch(error) {
console.log(error) // This prints properly (e.g., "ReferenceError: myRef is not defined")
functions.logger.error(`Unexpected error occurred:`, { error: error }) // This prints error object as: "error: {}"
}
Why does the error object appear empty when using functions.logger.error() and how can I fix it?
If I'm not mistaken, this is because your { error: error } object isn't a simple object, which means the logger won't interpret it as a jsonPayload.
See more details in the doc ("If the last argument provided is a plain object, it is added to the jsonPayload in the Cloud Logging entry") and in this Github issue.
Potential solutions are as follows:
functions.logger.error(`Unexpected error occurred:`, error) // Here error is a "simple object"
functions.logger.error(`Unexpected error occurred:`, { error: error.message })
or the solution detailed in the Github issue.

got some error massage in console when I try to update my field value in mongodb through express

My node app will crash when i send req for update the field value in my mongo db. The data will updated successfully, But The message will no show which is i provided in (
(err) => {
if (err) {
res.status(500).json({
error: "There was an error in server side!",
});
} else {
res.status(200).json({
message: "value updated successfully!",
});
}
}
)
Instead of showing above message. the mongo sent me (const err = new MongooseError('Query was already executed: ' + str);). this message and more :
MongooseError: Query was already executed: Todo.updateOne({ _id: new ObjectId("6243ed2b5e0bdc9ab780b4d9...
But I use each and every time different id and update with differen message.
when i check in db is that the old value updated or not, but nicely the old value updated. but no message or any thing i can't see in postman resposnse.Also in my console the mongodb throw me above error.
What ever happened I want to see my predefined err messages or successfully messages.
Finally, I got and understood the answer. Actually, I am a beginner programmer and developer that's why I made this problem and it took a lot of time to solve. I solved the problem within 3-5 minutes by removing async/await but I took a lot of time to dig out why it's working after removing async/await. Here is a basic concept of asynchronous programming if we use async/await we don't have to use callback again, Or if we use callback we don't need async/await Because it's just redundant. So, if we want to get data like we are getting from
callback(err,data) =>{
res.send(data);
}
then we just assigned our full thing in a variable like:
try{
const data=await (our code);
res.send(data);
}catch(err){
res.send(err.message);
}

io.connect() is not working and i can't figure what is the problem

[and this is the angular code ][1] this is my node js code
Please copy/paste your actual code. Screenshots are discouraged on SO.
Be sure to include ERROR HANDLING in all of your I/O operations. For example:
https://socket.io/docs/v4/client-initialization/
socket.on("connect_error", (err) => {
if (err.message === "invalid credentials") {
socket.auth.token = "efgh";
socket.connect();
}
});
... or ...
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/onerror
webSocket.onerror = function(event) {
console.error("WebSocket error observed:", event);
};
Your next step is to get a viable error message.
Please review the library's documentation to determine the "best" way to catch and handle errors for your particular application.

There is any way to handle errors with correct status code in NestJS or with GraphQL?

Actually, the GQL validation errors working correctly but when I throw the nestjs error with Exceptions of nestjs I don't get proper status code or exact error on the base array or inner objects the actual error found in the dept of the array. And in the browser network tab always show the 200 status even the nestjs throw an error, there is any way to catch the error which is thrown by the nestjs and correct status code in browser network tab when catch error?
The Apollo Server constructor accepts a formatError function that is run on each error passed back to the client. This can be used to mask errors as well as for logging and the in the NestJS you can use this method in your GraphQLModule mostly exists in the app.module.ts
GraphQLModule.forRoot({
....
...
formatError: (error) => {
const graphQLFormattedError = {
message:
error.extensions?.exception?.response?.message || error.message,
code:
error.extensions?.code || "SERVER_ERROR",
name: error.extensions?.exception?.name || error.name,
};
return graphQLFormattedError;
},
}),
I solved this type of problem by throwing grapqhl type error, where you can easily manage message and code.
throw new GraphQLError(
customMessage,
{
extensions: {
code: customCode,
},
},
);

Express Js not sending error object on res.json()

getUser: function(req, res){
Model.getUser({}, function(error, models){
if(error){
let response = {
code: 'ERR0001',
msg: 'Facing issues while ....',
err: error
}
res.json(response);
} else {
res.json(models)
}
}
};
Above code is working fine for all positive scenarios. But for error scenario I am not getting complete error message instead it shows 'err: {}'.
I have already registered JSON parser with Express app object.
Response I am getting in POSTMAN console in case error is
{
code: 'ERR0001',
msg: 'Facing issues while ....',
err: {}
}
As per my requirement it should display something like:
{
code: 'ERR0001',
msg: 'Facing issues while ....',
err: 'ERROR: whatever exception occurred on database operation...'
}
Please help me to understand cause of this issue.
Express is stringifying your JSON response when you use res.json().
However, because the Error object doesn't get handled by JSON.stringify() as you would expect, you're not seeing the content of it; like the stack trace property for example.
For details on what's happening with JSON.stringify() and the Error object, check out this other stack overflow answer (I won't duplicate that here):
https://stackoverflow.com/a/18391400/2387067
So, using a variation of that answer, I will do this when I want to send back a Javascript Error object to the client from Express:
function replaceErrors(key, value) {
if (value instanceof Error) {
var error = {};
Object.getOwnPropertyNames(value).forEach(function (key) {
error[key] = value[key];
});
return error;
}
return value;
}
function getPureError(error) {
return JSON.parse(JSON.stringify(error, replaceErrors));
}
and then make a call to it in my response like this:
res.status(500).json(getPureError(error));
The call to getPureError() stringifys the Error object and gets all of the properties because of the call to replaceErrors(). It then parses it back to a pure object. That pure object plays nicely with Express when the .json() call is made so you get all of your properties that you were expecting. It is a bit wasteful but you get the result you're looking for.
This results in my seeing the full, Error object; stack trace and all.
When I first encountered this problem, I was doing this:
res.status(500).json(error);
and I was getting back {} in my response on the server. It took me a bit of time to sort out what was happening there. I originally thought that I wasn't chaining that json() command incorrectly but I was. The actual problem was that the Error object doesn't behave like other objects with JSON.stringify() as described above.
I hope that helps you or at least someone else after all this time!

Resources