错误:未捕获(在承诺中):[object Object]

时间:2017-10-03 10:47:29

标签: javascript angular error-handling

@Injectable()
class MyErrorHandler implements ErrorHandler {

  handleError(error) {
    // exception occured in some service class method.
    console.log('Error in MyErrorhandler - %s', error);
      if(error == 'Something went wrong'){
       //do this.
     }else{
      //do this thing.
    }
  }
}

当在某个类'方法抛出异常时,MyErrorHandler类打印捕获的错误Error in MyErrorhandler - Error: Uncaught (in promise): [object Object] Error: Something went wrong.

问题1 :为什么错误显示为Error: Uncaught (in promise): [object Object]

问题2 :由于上述消息,即使在任何条件下if(error == 'Something went wrong')代码的情况下,也会始终读取else部分。如何解决此问题?

3 个答案:

答案 0 :(得分:2)

尝试添加

if(error.message == 'Something went wrong'){
}

而不是唯一的错误。因为错误是一个对象。

答案 1 :(得分:1)

需要您检查您的诺言中的答复...

您必须捕获解决拒绝 ...

通常发生这种情况是因为拒绝的值不是捕获值

例如

创建承诺...

promise= () => {
    return new Promise((resolve, reject) => {
      if (condition) {
         resolve(true);
      }else{
        reject(false);
      }
    });
}

并且这里捕获了承诺中所有可能的响应。

this.services.promise().then(
    (data) => {
       here capture your resolve
       },
    (err) => {
       here capture your resolve
    }
);

OR

 this.services.promise()
   .then((res) => {
       console.log('response in resolve = ', )});
    ).catch((err)=> {
      console.log('response in reject = ', err)
    })

答案 2 :(得分:0)

动产动产法。

`从'@ angular / core'导入{Injectable,ErrorHandler,Injector}; 从'./_alert.service'导入{AlertService};

@Injectable({   providerIn:'root' }) 导出类ErroresService实现ErrorHandler {

构造函数(私有sv_alert:AlertService){}

handleError(err:any){     const message = err.message吗? err.message:err.message.toString();     this.sv_alert.AlertaMensajeError(${ message });   } }`