退出从本机反应上传照片时出现未处理的错误

时间:2018-04-17 06:37:29

标签: javascript reactjs react-native error-handling

这是我的组件,用于从用户手机中选择和上传照片。它工作正常,期待当用户打开手机photolibrary然后决定取消而不选择任何上传的照片时,我会收到如下错误:

“YellowBox.js:82可能的未处理承诺拒绝(id:0): 错误:用户取消了图像选择“

我不知道在哪里以及如何捕获和处理错误,任何帮助?

<div class="line"></div>

3 个答案:

答案 0 :(得分:1)

如果用户取消选择图片,

ImagePicker.openPicker()将抛出错误。

尝试向您的代码添加catch,如下所示:

ImagePicker.openPicker(options)
.then(image => {
    // do your stuff
})
.catch(error => {
    // add this to your code
});

答案 1 :(得分:0)

ImagePicker.openPicker({
  cropping: true,
  height: 265,
  width: 265,
  mediaType: 'photo'
}).then(image => {
  const imagePath = image.path

  let uploadBlob = null

  const imageRef = firebase.storage().ref(`/users/${currentUser.uid}/profile`).child('dp.jpg')

  let mime = 'image/jpg'
  fs.readFile(imagePath, 'base64')
        .then((data) => {
          return Blob.build(data, { type: `${mime};BASE64` })
        })
      .then((blob) => {
        uploadBlob = blob
        return imageRef.put(blob, { contentType: mime })
      })
       .then(() => {
         uploadBlob.close()
         return imageRef.getDownloadURL()
       })
       .then((url) => {
         firebase.database().ref(`/users/${currentUser.uid}/profile`).update({
           profile_picture: url
         })
         let obj = {}
         obj['loading'] = false
         obj['dp'] = url
         this.setState(obj)
       })
       .catch((error) => {
         console.log(error + 'OPEN PICKER AGAIN')
       })
       .catch((error) => {
         console.log(error)
       })
       .catch((error) => {
         console.log(error)
       })
}).catch((callBack)=>{ // you forgot to add catch to this promise.
   console.log(callBack); // Please handle the callBack here.
  });
 }

答案 2 :(得分:0)

这里有一个对我有用的修复:

ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true,
    })
.then(image => {
    /*
image = {
    "cropRect": { "height": zzz, "width": sss, "x": aaa, "y": qqq },
    "height": xxx,
    "mime": "image/jpeg",
    "modificationDate": "1611843171000",
    "path": "file:///storage/emulated/0/Android/data/.../.....jpg",
    "size": 59579,
    "width": yyy
}
    */
})
.catch(error => {
    if (error.code === 'E_PICKER_CANCELLED') { // here the solution
      return false;
    }
});