React: Unhandled Rejection : Cannot read property 'data' of undefined - reactjs

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".

Related

Throwing custom exception in React

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?

TypeError: Cannot read property 'messages' of undefined

I'm trying to get the messages of an array of channel ids, and this is the code. The console.log does log the channel objects, so I know they're in there. However, on running this, it returns the TypeError "Cannot read property 'messages' of undefined"
console.log(filtered_channel_ids);
filtered_channel_ids.forEach((element) => {
const channel = client.channels.cache.get(element);
if (channel.messages) {
channel.messages
.fetch({limit: 10})
.then((message) => console.log(message.content));
}
});
I've also tried catching the error, but it still won't return anything.

Problem with webhooks and the role/permissions idea

I develop a bot with discord.js that uses things like msg.member.hasPermission("ADMINISTRATOR") or msg.member.roles.cache.has(teacherRoleID). Everything worked fine until I tried webhooks. By adding these two lines :
client.on('ready', () => {
client.user.setStatus("online")
client.user.setActivity("!help", {
type: "PLAYING",
});
superConsole(`Logged in as ${client.user.tag} in ${client.guilds.size} guilds!`);
const hook = new Discord.WebhookClient("ID", "secret token"); // THESE
hook.send("I am now alive!"); // LINES
});
(btw superConsole is a function)
Since then, the program did not work any more and always returned the same errors: (node:20736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of null & (node:20736) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of null
When I delete these 2 lines for the webhook, it works again. Why? I don't understand.
The permission and role things are in a message listener:
client.on('message', async msg => {
if (msg.member.hasPermission('ADMINISTRATOR') {
// some stuff here
}
if (msg.member.roles.cache.has(teacherRoleID) {
// some stuff here
}
});
The issue is that when you send a message from hook, it triggers the client's message event. Because a webhook isn't a guild member, msg.member will get undefined for messages sent from a webhook.
You would have to use something like this:
if (msg.member) {
if (msg.member.permissions.has('ADMINISTRATOR') {
// some stuff here
}
if (msg.member.roles.cache.has(teacherRoleID) {
// some stuff here
}
}

Getting error "Unhandled Rejection (TypeError): api_call4.json is not a function" even when error is caught in reactjs

While fetching the weather api, if disconnection occurs, error is thrown which is caught, and few seconds later the error is displayed on screen which is quite unpleasant. No idea of resolving this error.
App.js file
const api_call4 = await fetch(`https://api.weatherbit.io/v2.0/current?` +
`city=${city}&key=${API_KEY3}`).catch(error => toast.error('No Data Received',error))
const data4 = await api_call4.json();
console.log('DATA CURRENT', data4)
As you can see above error is caught, but still error is diplayed. Please see the image below. What is the best solution...
You have to change your flow to ensure that your api call is successful. One way would be to use try/catch blocks since you're using async/await. Something like:
try {
const api_call4 = await fetch(`https://api.weatherbit.io/v2.0/current?` +
`city=${city}&key=${API_KEY3}`)
const data4 = await api_call4.json();
console.log('DATA CURRENT', data4)
}
catch(error) {
toast.error('No Data Received',error)
}

unable to catch errors in react-native

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

Resources