tohokuaikiのチラシの裏

技術的ネタとか。

axiosでParallel実行する時のエラーハンドリングがよくわからない

axiosで並列して全部終わったら…というやつ。

axios.all([
    axios.get('/api/user/'),
    axios.get('/api/image')
]).then(([res1, res2]) => {
    this.user = res1.data;
    this.image = res2.data;
}).catch(err =>{
    console.log(err);
});

ってやると、2つgetしたうちの最初のエラーしかcatchしてくれない。

個々のエラーを見たかったら

axios.all([
    axios.get('/api/user/').catch(err => { /*  error処理 */ }),
    axios.get('/api/image').catch(err => { /*  error処理 */ })
]).then(([res1, res2]) => {
    this.user = res1.data;
    this.image = res2.data;
});

という感じに個々のaxiosにcatchを付ける。でも、これだとthenにいっちゃう。

それが嫌なら

axios.all([
    axios.get('/api/user/').catch(err => { /*  error処理 */ throw(err); }),
    axios.get('/api/image').catch(err => { /*  error処理 */  throw(err);})
]).then(([res1, res2]) => {
    this.user = res1.data;
    this.image = res2.data;
}).catch(err =>{
    console.log(err);
});

ってやると、catchできるけどそれって最初のとあんま変わんないっていう…。