axiosでのエラーハンドリング
これはaxiosに限らずajaxでも同じだけど、
例えば
axios.get('http://localhost:3001/users') .then(response => { console.log('status:', response.status); // 200 console.log('body:', response.data); // response body. }).catch(err => { console.log('err:', err); });
とGet通信した場合にその引数の中身がなんじゃろと思ってたんですよね。Promiseで返ってくればdataってプロパティはありますが そんな事を知らない当時の私。
axiosの場合だけかな?thenの引数は
.then(function(response) { console.log(response.data); // レスポンスデータ console.log(response.status); // ステータスコード console.log(response.statusText); // ステータステキスト console.log(response.headers); // レスポンスヘッダ console.log(response.config); // コンフィグ });
と書けて、catchの引数は
.catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); // 例:400 console.log(error.response.statusText); // Bad Request console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config);
と書ける。そんなメモ。