Reputation: 2356
I've got a function where I submit a large form and it makes multiple API calls. I tried to separate it into smaller functions cause there is some additional logic that depends on API response.
I wrapped each API call within a function in try ... catch
so that I have more control over the errors. The problem is that I need to terminate the parent function whenever one of the child function throws an error and I can't figure out the clean way of doing that.
So the code is the following:
const func1 = async() => {
try {
// api call + logic
} catch (error) {
// show error toast and terminate formSubmit function
}
}
const func2 = async() => {
try {
// api call + logic
} catch (error) {
// show error toast and terminate formSubmit function
}
}
const func3 = async() => {
try {
// api call + logic
} catch (error) {
// show error toast and terminate formSubmit function
}
}
const formSubmit = async () => {
await func1()
await func2()
await func3()
}
Upvotes: 0
Views: 960
Reputation: 486
Just throw a new error or rethrow the error and then add a new handler in your formSubmit function.
const func1 = async() => {
try {
// api call + logic
} catch (error) {
// show error toast and terminate formSubmit function
throw new Error("...");
}
}
const func2 = async() => {
try {
// api call + logic
} catch (error) {
// show error toast and terminate formSubmit function
throw new Error("...");
}
}
const func3 = async() => {
try {
// api call + logic
} catch (error) {
// show error toast and terminate formSubmit function
throw new Error("...");
}
}
const formSubmit = async () => {
try {
await func1()
await func2()
await func3()
} catch(e){
// do what needs to be done on error
}
}
Upvotes: 1