Reputation: 25
I was testing my code to see what would happen if I tried to register an already registered user and when I did that I got the error in the title with the expected error status code, however, I do have a catch statement so I'm not sure why the error is not being caught.
This is the state of the class:
state = {
data: { username: "", password: "", name: "" },
errors: {},
};
This is my code:
doSubmit = async () => {
try {
await userService.register(this.state.data);
} catch (error) {
if (error.response && error.response.status === 400) {
const errors = { ...this.state.errors };
errors.username = error.response.data;
this.setState({ errors });
}
}
};
export function register(user) {
http.post(apiEndpoint, {
email: user.username,
password: user.password,
name: user.name,
});
}
Any help would be appreciated!
Upvotes: 1
Views: 2425
Reputation: 56
try catching the error in the register
function like this:
export async function register(user) {
try {
http.post(apiEndpoint, {
email: user.username,
password: user.password,
name: user.name,
})
} catch (error) {
if (error.message === 'Timeout'
|| error.message === 'Network request failed') {
...
data.status = 400
data.errorMessage = "Some error message"
return data;
}
//if (catch other requests...)
}
}
Then wherever you call the function...
doSubmit = async () => {
let result = await userService.register(this.state.data);
if (result.status == 200) {
do something
} else if (result.status == 400) {
do something else
}
};
This isn't the best example but hope it helps!
Upvotes: 1
Reputation: 1439
catching error in register
function instead of doSubmit
:-
register
function:-export async function register(user) {
try {
await http.post(apiEndpoint, {
email: user.username,
password: user.password,
name: user.name,
});
} catch(error) {
return error
}
}
doSubmit
function:-doSubmit = async () => {
let res = await userService.register(this.state.data);
if (res.response && res.response.status === 400) {
const errors = { ...this.state.errors };
errors.username = res.response.data;
this.setState({ errors });
}
};
Upvotes: 0