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
Related
So I have this function which sends request to the API and I want to throw exception when requests fails:
async function getCampaigns() {
try {
const response = await api.get('/cars');
setSelectItems(
response.map((item: Car) => ({
label: item.carLabel,
value: item.carValue
}))
);
setLoading(false);
} catch (error: any) {
const exception = new Exception(error);
exception.kind = 'recoverable';
throw exception;
}
}
I created custom exception to handle errors in this code:
Exception.ts
type ExceptionType = 'nonrecoverable' | 'recoverable';
export class Exception extends Error {
public kind: ExceptionType;
constructor(message?: string, options?: ErrorOptions) {
super(message, options);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, Exception);
}
this.kind = 'nonrecoverable';
this.name = 'Exception';
}
}
However I am getting the following error whenever I get error response:
Unhandled Runtime Error
Exception: AxiosError: Request failed with status code 401
which is pointing at this line:
const exception = new Exception(error);
Not sure why is this happening and how can I throw the custom error like this?
EDIT:
So the actual problem here is that, when I catch the error and throw custom one based on the error caught I throw it again in the catch block. I think this results in the custom error that is being thrown uncaught.
And because the custom error is uncaught, in Next.js development mode I get this error Overlay telling me about unhandled error...
Even though I have ErrorBoundary component that works as inteded (so redirects to the error component) but still Next.js overlay is displayed. So I am not sure how should I handle the custom error inside catch block in this situation? Is this correct approach already and should I leave it as it is or is there some better wayt to do this?
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.');
});
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));