LoginSignup
2
2

More than 5 years have passed since last update.

Ajaxで画像ダウンロードしたときに、エラーが起こったら?

Last updated at Posted at 2018-07-25
function download () {
  return axios.get('download_url', { responseType: 'blob' })
    .then(res => Promise.resolve(res), error => Promise.reject(error))
}

としたときに、どうやってエラーを表示するか?とりあえずメモ

download().then(res => {
  // FileSaverを使って保存
  FileSaver.saveAs(new Blob([res.data], { type: 'image/jpeg' }))
}, async error => {
  try {
    let resText = await new Promise(resolve => {
      let reader = new FileReader()
      reader.addEventListener('loadend', () => {
        resolve(reader.result)
      })
      reader.readAsText(error.response.data)
    })
    // エラー表示
    alert(JSON.parse(resText))
  } catch (e) {

  }
})
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2