Microsoft Bot framework error in azure Webchat - dialog

I am getting error while calling the this.dialog inside the onmessage function.
this.onMessage(async (context, next) => {
if(d == "true")
{
await context.sendActivity("token is there");
}
else{
await this.dialog.run(context, this.dialogState);
await next();
}
}
d value will be false so control goes to else part but after going to else part I am getting error.
Error message: The bot encountered an error or bug.
To continue to run this bot, please fix the bot source code.

Related

How to send a custom status and error message if no data found using Node.JS/express and axios?

If no user is found (it's just an example to understand error handling), I want to send a custom message such as
res.status(404).send('no user');
my client never receives that and instead I get:
[AxiosError: Request failed with status code 404]
What am I doing wrong? I cannot find any other solution and have been researching for a while now. Also wonder how I could send a custom status (if no data found it's 404 but what if I want to send 200)?
node express
router.get('/getuser', async (req, res) => {
try {
const user = await User.findOne({_id: req.user._id});
if (!user) {
res.status(404).send('no user');
} else {
res.status(200).send(user)
}
} catch(error) {
res.status(500).send(error)
}
});
frontend
const trycatch = async () => {
try {
const response = await axios.get(example.com/trycatch)
return response.data;
} catch (error) {
console.log(error)
}
}
Responses with a status code of 400 or more are treated as errors by axios. As a consumer, you can only react to that in the catch (error) clause, for example:
catch (error) {
switch (error.response.status) {
case 404: return "no user"; break;
default: return error.response.data;
}
}
But you can influence which statuses cause errors with the validateStatus option of the axios request.
Summary: Either you distribute your code between the try and the catch block, where the try block code handles successes (status < 400) and the catch block handles errors (status ≥ 400). Or you use validateStatus to change what counts as a success and what counts as an error.

How to completely ignore permission errors in Discord.JS?

How can I ignore all bot's permission errors in Discord.JS? I have already the checking bot's permissions functions, but this function doesn't work on the channels permissions. You can answer how can I ignore all bot's permission errors (if it can) or how to check permissions even in the channels permissions.
There is my error (it's the same as not checking permissions):
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Permissions
You can check GuildMember#permissions to see if the client has a certain permission in a guild.
// Example
const botMember = message.guild.me;
if (!botMember.permissions.has('KICK_MEMBERS')) {
// Code
} else {
// Error Handling
}
Additionally, you can use GuildMember#permissionsIn() to check the client's permissions in a certain channel
const botMember = message.guild.me;
if (!botMember.permissionsIn(CHANNEL).has('permission')) {
// Code
} else {
// Error Handling
}
As shown in other answers, you can also handle the promise rejection using .catch() or catch () {}
Ensure you're awaiting any promise function when using async/await + try/catch
// Example
try {
await message.channel.send(...);
} catch (err) {
// Handle err
}
message.channel.send(...)
.then(msg => {})
.catch(err => {
// Handle err
});
You could solve this in multiple ways
Wrap it in a try/catch statement
This would look something like:
try{
// Do this
} catch (error) {
// Do that
}
You caould use a .catch() function
role.doSomething().catch((error) => {
// Do that
})
If you wanted to see if the error code was due to a missing permission you could do:
const { Constants } = require("discord.js")
try{
// Do this
} catch (error) {
// Do that
if(error.code === Constants.APIErrors.MISSING_PERMISSIONS){
// Do this and that
}
}
You could try exception handling, if you're just wanting the bot to proceed without crashing it.
I would recommend at least logging the error in console. For this example I'll use a try/catch block.
try{
await doSomethingThatRequiresPermissions();
}catch(error){
console.log("Error: "+error+" at doSomethingThatRequiresPermissions");
}
NodeJS error handling documentation
Discord.js specific permission handling
Edit: I don't have access to my server at the moment (as I'm at work) but I will test this later to find a more comprehensive answer.

React frontend doesn't receive return from nodejs backend in Reactjs + Nodejs App

My backend login process is running on a Nodejs 12.16.1. The code is following:
router.post("/elogin", async (req, res) => {
try {
if (!req.body.userName || !req.body.password) throw new Error("No match"); //<<==this line causes error and jump to catch
let emp = await Employee.findOne({where: {username, password}});
if (!emp) throw new Error("No match!");
return res.status(200).send(_.pick(emp, ['id', 'cell', 'cell_country', 'name']))
} catch(err) {
return res.status(400).send("Hi Not working right now"); //<<===this return stuck and never come out.
}
});
In debug the code stuck at drainQueues in Bluebird which is a promise library according to online info. The execution never ends and stuck here. This is a normal return and I don't see how it shall be stuck.
The front end is React and Fetch. The action type does not matter. The get is stuck as well.
You try to use postman to see if it returns. If there is, then there may be a problem with the backend code

sequelize handling rejection in the create statement - catch not firing

The sequelize create statement has an error and I would like to handle that error. Since the create statement has the error I need to handle promise rejection. How do I do that in code? Tried to look at the sequelize documents but unable to work it out.
db.Employee.create(empData,
{
include:[
{
model: db.EmployeeDetails
}
]
}).then(function(newEmployee){
res.json(newEmployee);
}).catch(function(err){
return next(err);
});
The error is on the create and so the webpage just gives an internal server error. I was under the impression that the catch was something that handled the promise rejection and failure. In this case, how can I handle the promise rejection in code. An example would be greatly appreciated.
By doing next(err), by default, you send a 500 Internal Server Error message. If you use Express, and want to show a custom error, just append a status code which is not 5xx to the error:
General Usage:
const err = new Error("my custom error")
err.statusCode = 400
next(err)
In your snippet, do:
db.Employee.create(empData, {
include:[
{
model: db.EmployeeDetails
}
]
}).then(function(newEmployee){
res.json(newEmployee);
}).catch(function(err){
err.statusCode = 400
next(err);
});
If you haven't set your error handler in Express you will need to add somewhere at the end of the main file this:
// Error Handler
app.use(function(err, req, res, next) {
console.error(err)
if (!err.statusCode) err.statusCode = 500;
let msg = err.message
// Do not expose 500 error messages in production, to the client
if (process.env.NODE_ENV === "production" && err.statusCode === 500) {
msg = "Internal Server Error"
}
res.status(err.statusCode).send(msg)
})
Your webpage showing a 500 error means the issue was caught / working as intended. What you need to do is figure out how to handle displaying that error in a pretty format - this being a UI task. If you want a 'patch' for hiding the issue, change your return to a res. This will trick your browser with a 200 status and hide the error.
I do want to add, I recommend trying async/await for sequelize. There's a good amount of usage examples with it.
Promise
db.Employee.create(empData,
{
include:[
{
model: db.EmployeeDetails
}
]
}).then(function(newEmployee){
res.json(newEmployee);
}).catch(function(err){
// Temporary patch
res.json("pretty error message");
});
Async/Await version
async function createEmployee(empData) {
try {
return await db.Employee.create(empData, {
include:[ { model: db.EmployeeDetails } ]
});
} catch (err) {
// Handle error here
return err;
}
}

Catch 404 on xhr.js, when Axios GET is called and express server sends .json()

On my client Vue.js application the console gives me an 404 error, when calling my express API, with an invalid API token.
E.g. calling http://localhost:8081/confirmation/invalidToken
gives, me
xhr.js?b50d:172 GET http://localhost:8081/confirmation/a 404 (Not Found)
Of course it is possible for someone to use that invalid link, so I want to handle these errors instead of printing the error on the console.
If on my express server side, I send the response, like this:
return res.status(404);
Then the console error disappears.
Edit: However this only seems to be the case, because the request is not finished and it's waiting. After a while, the console logs a "net::ERR_CONNECTION_RESET" error.
It's only appearing if I send the response like this:
return res.status(404).send({
message: 'No valid link!',
error,
});
or this:
return res.status(404).send({
message: 'No valid link!',
error,
});
Catching on client side is not working for this problem.
public async sendConfirmation(token: string): Promise<any> {
try {
return axios.get(this.baseURL + '/confirmation/' + token);
} catch (error) {
// tslint:disable-next-line:no-console
console.log(error.response);
}
}
sendConfirmation(this.token)
.then((res) => {
// tslint:disable-next-line:no-console
console.log(res);
if (res.status === 404) {
throw new Error("404");
}
this.data = res.data;
if (res.status === 201) {
this. messagetype = 1;
} else if (res.status === 200) {
this.messagetype = 2;
}
})
.catch((err) => {
this.messagetype = 0;
// tslint:disable-next-line:no-console
// console.log(err );
});
Anyone knows a way to catch that console error, not having to remove the custom message in the server result?
I had same error in heroku in a webpack project with variables environments, i had path of .env file set to local path like c:/project/.env, so the variable of server always return undefined, changing path to relative one fixed the bug:
if (process.env.REACT_APP_ENV === "development") {
require("dotenv").config({
path: ".env.development",
});
}
also check the .env file make sure there is no quotes:
SERVER_URI=https://yourApp.com
and not this:
SERVER_URI="https://yourApp.com"
you have to stringify it later in webpackconfig.
this may help someone or give him a hint.
Well, it's a browser behaviour, that shows the error.
Certain response codes, will in some browsers throw those console messages.
There seems no way to prevent this in a project.

Resources