Tengo una función en la que envío un formulario grande y hace varias llamadas a la API. Traté de separarlo en funciones más pequeñas porque hay una lógica adicional que depende de la respuesta de la API. Envolví cada llamada API dentro de una función en try ... catch para tener más control sobre los errores. El problema es que necesito terminar la función principal cada vez que una de las funciones secundarias arroja un error y no puedo encontrar la forma limpia de hacerlo.
Entonces el código es el siguiente:
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() }Simplemente lanza un nuevo error o vuelve a lanzar el error y luego agrega un nuevo controlador en tu función formSubmit.
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 } }