Cannot read property 'findIndex' of undefined bot - javascript

I am trying to put an option in a bot and I get the error when I run the command. !ddd is the command
obterInfoDDD: async(DDD)=>{
try {
const githubGistDDD= await axios.get(" here I put the github directory ddd.json")
const estados = githubGistDDD.data.estados
const indexDDD = estados.findIndex(estado => estado.ddd.includes(DDD))
if(indexDDD != -1){
var resposta = criarTexto(msgs_texto.utilidades.ddd.resposta, estados[indexDDD].nome, estados[indexDDD].regiao)
return resposta
} else {
throw new Error(msgs_texto.utilidades.ddd.nao_encontrado)
}
} catch(err){
var errors = [msgs_texto.utilidades.ddd.nao_encontrado]
if(!errors.includes(err.message)){
consoleErro(err.message, "API obterInfoDDD")
throw new Error(msgs_texto.utilidades.ddd.erro_servidor)
} else {
throw err
}
}
}

Related

How to handle image upload with predefined error handling for form

I'm trying to include an optional image upload in my express app, but, with the way I've designed the app, I think it's trying to pass the image name from the body instead of using the separate function I've created for it. Is there any workaround for it to verify the file without digging into the models?
posts.post("/", async (req, res) => {
const postId = uuidv1();
const userId = req.query.userId;
let checkUser = await User.getById(userId);
if(checkUser.length === 0) {
User.create(userId);
}
const dateCreated = new Date().toLocaleString('en-GB');
const dateUpdated = dateCreated;
let bodyValues = [];
let invalid = false;
let picUpload;
if (req.files === undefined || req.files === null) {
picUpload = 'none';
} else {
picUpload = req.files.image;
picUpload.mv('./images' + picUpload.name);
}
Post.fillable_properties.map(function (v) {
if (req.body[v] === null || req.body[v] === undefined)
invalid = true;
else bodyValues.push(req.body[v]);
});
bodyValues = [postId, ...bodyValues, picUpload, userId, dateUpdated, dateCreated];
if (!invalid) {
const [results, error] = await Post.create(bodyValues);
if (error.length == 0 && results.affectedRows == 1)
res.status(201).json(response.prepare(201, results, error));
else
res.status(400).json(response.prepare(400, results, error));
} else {
res.status(400).json(response.prepare(400, [], [{ "message": "Missing data" }, bodyValues]));
}
});
It sets invalid as true probably because the image is not part of the request body, but I don't know how to handle that.
Ultimately I worked around it within the client to set the file name to an empty string if there's no image to be uploaded, while not ideal it solves the issue in the meantime.

Discord.JS TypeError: message.author.hasPermission is not a function

I was working on a command for a discord.js bot, and whilst making a command command (which turns commands on/off), I've been encountering errors.
When I use the .hasPermission function, I get the error encountered in the title:
TypeError: message.author.hasPermission is not a function
I do not believe it's a problem with my code, as the constructor works on other commands, but I'm open to suggestions. My code is below:
module.exports = {
name: 'module',
description: 'Turn commands on/off',
execute(message, args) {
// required
const Discord = require('discord.js');
const db = require('quick.db')
var randomExt = require('random-ext');
//required end
var commands = ['changelog','invite','prefix','balance','bankrob','beg','deposit','gamble','job','rob','work','afk','avatar','botinfo','serverinfo','userinfo','level','setlevel','ban','kick','mute','purge','unban','unmute','warn','warnings']
let user = message.author;
let commandSelect;
const permissionEmbed = new Discord.MessageEmbed()
.setTitle('You dont have permission to do this')
const commandFail = new Discord.MessageEmbed()
.setTitle('There is no command with that name!')
const argsError = new Discord.MessageEmbed()
.setTitle('Usage: `command <command> <on/off>`')
const completeEmbed = new Discord.MessageEmbed()
.setTitle(`Command \`${args[0]}\` is now \`${args[1]}\``)
if (!message.author.hasPermission('ADMINISTRATOR')) {
return message.channel.send(permissionEmbed);
} else if (user.hasPermission('ADMINISTRATOR')) {
if (!args[0] || !args[1]) {
return message.channel.send(argsError);
} else if (args[0] != 'on' && args[0] != 'off') {
return message.channel.send(argsError);
}
for (i = 0; i > commands.length; i++) {
if (args[0] == commands[i]) {
return commandSelect = commands[i];
}
}
if (commandSelect = null || commandSelect == undefined) {
return message.channel.send(commandFail);
} else {
db.set(`${message.guild.id}.${commandSelect}`, 'false')
return message.channel.send(completeEmbed);
}
}
},
};
I also think it's worth mentioning that when I run the command with arguments, p!command ban off, I get the error TypeError: Discord.MessasgeEmbed is not a constructor instead.
message.author returns a User and message.member returns a GuildMember; the author of the message as a guild member.
Discord Users don't have permissions, guild members have. You can only check if a member has certain permissions, so you need to change your code to:
if (!message.member.hasPermission('ADMINISTRATOR')) {
return message.channel.send(permissionEmbed);
}
// you don't need else or else if as this part is only executed if member
// is an administrator
if (!args[0] || !args[1]) {
return message.channel.send(argsError);
} else if (args[0] != 'on' && args[0] != 'off') {
return message.channel.send(argsError);
}
// ...

how to make if there is no file it will do nothing

hey so I'm trying to const some JSON
const cidc = require('./cid/cid.json')
const dc = require('./details/cid.json')
const lc = require('./lik/cid.json')
if(!cidc){
return
}else{
fs.unlinkSync('./src/main/setting/cid/cid.json')
} if(!dc) {
return
}else {
fs.unlinkSync('./src/main/setting/details/cid.json')
} if (!lc){
return
}else {
fs.unlinkSync('./src/main/setting/lik/cid.json')
}
so I'm trying to delete the dc file and it error
how can I make if there is no such file named that it will do nothing (aka return nothing)
and if there is a file named that it will const it to a variable
Since require throws an error of Error: Cannot find module ... and you don't catch those errors, your script will fail.
You could define a new require-function where you catch the error and return undefined:
function safeRequire(path) {
try {
return require(path);
} catch(err) {
return undefined;
}
}
Then use this function in your script:
const cidc = safeRequire('./cid/cid.json')
const dc = safeRequire('./details/cid.json')
const lc = safeRequire('./lik/cid.json')
// rest of your code
Also you can simplify your if/else conditions by inverting the condition:
if (cidc) {
fs.unlinkSync('./src/main/setting/cid/cid.json')
}
if (dc) {
fs.unlinkSync('./src/main/setting/details/cid.json')
}
if (lc){
fs.unlinkSync('./src/main/setting/lik/cid.json')
}
Alternatively you don't even need to use require at all, just check if the files exist using e.g. fs.access(...).
You could directly use unlink with try catch without any requires
function unlink(filePath) {
try {
fs.unlinkSync(filePath);
} catch (e) {
//ignore
}
}
unlink('./src/main/setting/cid/cid.json')
unlink('./src/main/setting/details/cid.json')
unlink('./src/main/setting/lik/cid.json')

Getting a wrong Error response in catch block when using along with async await

async function run() {
try {
const data = await VarifyPanDetails(
leadData.leadId,
leadData.leadApplicantId,
doc_id,
{
name: sectionValues.panDetails.fullName,
panNumber: sectionValues.panDetails.panNumber,
dob:
sectionValues.panDetails.year.value +
'-' +
sectionValues.panDetails.month.value +
'-' +
sectionValues.panDetails.date.value,
fatherName: sectionValues.panDetails.fatherName
}
);
const { verified, message } = data;
if (verified === false) throw new Error('VARIFICATION_FAILED');
else throw new Error('VARIFICATION_SUCCESS');
} catch (err) {
if (err.message === 'VARIFICATION_FAILED')
throw new Error('VARIFICATION_FAILED');
else if (err.message === 'VARIFICATION_SUCCESS')
throw new Error('VARIFICATION_SUCCESS');
else throw new Error(err);
}
}
await run();
hi i was trying to get the error in catch(err) block if in case the VarifyPanDetails api above fails , but when it does it giving enter image description here if u console it, but network tap its showing enter image description here ,
how its not showing the throwing the same error as network tab i.e err in the console should have err.status===400 and err.message==="Invalid PAN Number" but instead of that its showing err.message:Error.false

Declaring Custom Exceptions to use with Firestore Callable Functions and VueJS

This far, I tried
A
class MyException extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
exports.MyException = MyException;
VueJS says "exports is not defined"
If I simply did
B
exports.MyException = () => {}
then Firebase says MyException is not a constructor. When I
throw new MyException()
Actually, once the exception is passed through callable functions, would it still be an instanceOf?
Should I just go with
C
try {
let d = await db.collection('x').document('y')
if (!d.exists) {
let e = new Error('Document Does not Exist')
e.code = 'ERR_NO_DOCUMENT'
throw e
}
else {
return d.data()
}
}
Is C a good practice?
As explained in the documentation for Callable Cloud Functions:
To ensure the client gets useful error details, return errors from a
callable by throwing (or returning a Promise rejected with) an
instance of functions.https.HttpsError.
So doing
try {
let d = await db.collection('x').document('y')
if (!d.exists) {
let e = new Error('Document Does not Exist')
e.code = 'ERR_NO_DOCUMENT'
throw e
}
else {
return d.data()
}
}
will not work.
You need to do, in your Callable Cloud Function, something like:
try {
let d = await db.collection('x').document('y')
if (!d.exists) {
let e = new Error('Document Does not Exist')
e.code = 'ERR_NO_DOCUMENT'
throw e
}
else {
return d.data()
}
} catch (error) {
throw new functions.https.HttpsError('internal', error.message);
}

Categories