I have a code fragment like this:
(...).catch(e) => {
if(e.response.status === 401) {
console.log("Wrong username or password")
} else {
console.log(e.statustext)
}}
And I have error like this: Unhandled Exception (TypeError): cannot read property status of undefined
How can I fix it?
catch block is passed an Error object and it doesn't contains any property named response.
Inside the then() block, check if status code is 401, if it is, throw an Error with the message "Wrong username or password" and inside the catch block, log the message using Error.prototype.message
.then(response => {
if (response.status === 401) {
throw new Error("Wrong username or password");
}
....
})
.catch(e) => console.log(e.message));
Related
Hello and thank you in advance!
const comprarCapsula = () => {
const compraCapsula = async () => {
console.log("Iniciando transacción...");
// ------------------------
const pago = web3.utils.toWei(precioFinal.toString(), 'ether');
// Mensaje de información
infoAlert();
// Petición al SC
const transaction = await contract.myFunction(cantidad, {
from: props.currentAccount,
value: pago.toString()}
).then((result) => {
console.log("RESULT:", result);
successAlert(result.tx);
}).catch((error) => {
console.error("TESTING: ", error.message);
errorAlert(error.message);
});
console.log("TRANS: ", transaction);
// ------------------------
}
contract && compraCapsula()
}
My application detects when I cancel the operation with MetaMask (error) but if the Smart Contract throws an error it is not picked up by the catch.
MetaMask - RPC Error: Internal JSON-RPC error.
Object { code: -32603, message: "Internal JSON-RPC error.", data: {…} }
Data: Object { code: 3, message: "execution reverted: Exception: must have minter role to mint"
Error "must have minter role to mint" its in my Smart Contract.
Why? I'm trying several ways to collect the RPC errors that Metamask throws but I can't find the way.
Could you check calling your contract function as such:
contract.myFunction.call
rather than
contract.myFunction
I had a similar problem when developing a contract. call can be used to see whether the function will throw an error - especially structural, modifier checking wise - but only using call will not invoke the full behaviour of the function. After checking for errors with call, you can call the function again.
Function calls with call enabled us to catch those kind of errors. I used such a structure then:
await contract.myFunction.call(`parameters...`)
.then(
contract.myFunction(`parameters...`)
)
I have sign up page and when user press the button got some errors if there are any. But when inputs are correct and there is no errors, i got an another error:
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
Heres my code:
try {
const response = await signup(body);
push('/login');
} catch (error){
if (error.response.data.validationErrors) {
setErrors(error.response.data.validationErrors);
}
}
try {
const response = await signup(body);
push('/login');
} catch (error){
if (error?.response?.data?.validationErrors) {
setErrors(error?.response?.data?.validationErrors);
}
}
please try this as the condition does not getting data from the response so you can use the fallback
I think there is no object called "data" in your response. Try to log your response and see whether there is an object called "data".
I don't know exactly how to use catch err, send a message instead of giving an error when it blocks the bot in the private message I want to do.
This code:
try{
message.member.send("trying private message.")
} catch(e) {
message.channel.send("Your private message is closed.");
};
When I get an error the catch err part doesn't work.
Sending a message returns a promise. You can handle the promise error by using the catch() method.
message.member.send('Trying to send a DM!')
.catch(error => {
console.log(error);
message.channel.send('Your DMs are closed.');
});
Purpose: To ban unauthorised users who kick members out of my server.
Code:
client.on("guildMemberRemove", async member => {
const FetchingLogs = await member.guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_KICK",
});
const kickLog = FetchingLogs.entries.first();
if (!kickLog) {
return console.log(red(`${member.user.tag} was kicked in ${member.guild.name} but nothing was registered in the audit log...`));
}
const { executor, target, createdAt } = kickLog
if (target.id === member.id) {
console.log(greenBright(`${member.user.tag} got kicked in ${member.guild.name}, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
member.guild.member(executor).ban({
reason: `Unauthorised Kick`
}).then(member.guild.owner.send(`**Unauthorised Kick By:** ${executor.tag} \n**Victim:** ${target.tag} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
})
Result: It bans the executor but it still throws this error:
(node:10272) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ban' of null
Could you please tell me why this is happening and what I could to remove this error. All help appreciated ;)
This is the offending line:
member.guild.member(executor).ban(....
You supply member.guild.member an executor object and it returns null, then it tries to call the function ban on a null object and you get the error.
Maybe try sending it the executor.id instead, like so:
member.guild.member(executor.id).ban
If you want to ban somebody from a guild you can do this by writing:
member.guild.members.ban(executor.id, { reason: "/* Your reason */" })...
Sources:
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=ban
and my experience with discord.js
How Can I handle error in React-Native
So this is my error enums
export const frontendErrors = {
INVALID_PHONE_NUMBER_ENTERED: 'Sorry you have entered invalid phone number'
}
From my phoneAuth.js file, I am throwing error in catch statement like this
catch (err) {
const errorSearch = 'auth/invalid-phone-number'
if (err.message.includes(errorSearch)) {
throw new Error(frontendErrors.INVALID_PHONE_NUMBER_ENTERED)
}
And When I catching the error in the parent component
catch (error) {
console.log(error)
this.dropDownAlertRef.alertWithType('error', 'Error', error)
}
in the log I am getting my error as an object and like this
Error: Sorry you have entered invalid phone number
The dropdownAlertRef takes in string so it is logging an empty object i.e.
this.dropDownAlertRef.alertWithType('error', 'Error', 'Invalid phone number')
this will log error.
What have I tried?
Doing, console.log(error.Error) gives undefined. How can I access my error?
You can do something like this.
console.log(error.message)
For more refrence you can refer here