In the chained promise function, how to determine which promise threw the error

I need to implement in a chained promise function, any function error in the middle terminates the program, and can catch the error function, and then perform different operations according to different error functions. How can the following code be improved?

do not bring information in the error object

function f1(){
    return new Promise((resolve,reject) =>{
        setTimeout(() =>{
            reject("err");
        },1000)
    })
}

function f2(){
    return new Promise((resolve,reject) =>{
        setTimeout(() =>{
            reject("err");
        },1000)
    })
}

function f3(){
    return new Promise((resolve,reject) =>{
        setTimeout(() =>{
            reject("err");
        },1000)
    })
}

const foo = () =>{
    return f1().then(() =>{
        return f2();
    }).then(() =>{
        return f3();
    }).catch(err =>{
        // 
        return err;
    })
} 

foo();

if every function sends an asynchronous request to the backend, the format of the data returned by the backend must be fixed, that is, we cannot judge which function threw the error based on the data returned by the backend. What should I do?

Thank you for your help!

Feb.26,2021

reject put useful information in


function f1(){
    return new Promise((resolve,reject) =>{
        setTimeout(() =>{
            reject("err1");
        },1000)
    })
}

function f2(){
    return new Promise((resolve,reject) =>{
        setTimeout(() =>{
            reject("err2");
        },1000)
    })
}

function f3(){
    return new Promise((resolve,reject) =>{
        setTimeout(() =>{
            reject("err3");
        },1000)
    })
}

const foo = () =>{
    return f1().then(() =>{
        return f2();
    }).then(() =>{
        return f3();
    }).catch(err =>{
        // 
        console.log(err);
        return err;
    })
} 

foo();

two ways

  1. reject throws Error objects with information

    function f1(){
        return new Promise((resolve,reject) =>{
            setTimeout(() =>{
                reject(new Error("f1 err"));
            },1000)
        })
    }
  2. output error messages in the second parameter function of each then method

      

    I think I also know

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1c18e80-3311d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1c18e80-3311d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?