【问题标题】:Proper error handling - in javascript/Ionic正确的错误处理 - 在 javascript/Ionic 中
【发布时间】:2019-01-30 20:28:31
【问题描述】:

我正在开发 Ionic 3 应用程序,该应用程序在蓝牙打印机上打印账单。而且我有点迷茫,如何正确处理这段代码中的错误:

  print(billToPrint){
    return this.bluetoothSerial.list().then((data)=>{
      if(data.length==0) throw new Error("no printer connected");
      console.log(data);
      console.log(data[0]);
      let subscription=this.bluetoothSerial.connect(data[0].address).subscribe(data=>{
        console.log("subscribnuto",data);
        this.bluetoothSerial.write(billToPrint).then((data)=>{
          console.log("data success", data);
        });
        subscription.unsubscribe();
      },err=>{
        throw new Error("Connection to printer failed");
      });
    },err=>{
      console.log(err);
    });
  }

在这种情况下处理错误的正确方法是什么?我希望错误与具体的错误消息一起传播,因此我可以在我的页面中轻松处理它们(此打印方法正在服务中)并显示带有错误消息的警报。有任何想法吗?还是代码结构不好?

【问题讨论】:

    标签: javascript angular ionic-framework error-handling


    【解决方案1】:

    而不是抛出这些错误。您可以使用 alert() 通知他们。

    print(billToPrint){
        return this.bluetoothSerial.list().then((data)=>{
          if(data.length === 0){ Promise.reject(new Error("no printer connected"));}
          // console.log(data);
          // console.log(data[0]);
          let subscription=this.bluetoothSerial.connect(data[0].address).subscribe(data=>{
            if(data){
               // console.log("subscribe",data);
               this.bluetoothSerial.write(billToPrint).then((data)=>{
                 // console.log("data success", data);
                 Promise.resolve(true);
               });
               subscription.unsubscribe();
            }else{
             Promise.resolve(false);
            }
          },err=>{
            Promise.reject(new Error("Connection to printer failed"));
          });
        },err=>{
          Promise.reject(new Error("error your processing your request"));
        });
      }
    

    【讨论】:

    • 感谢回答,但显示来自提供程序类的警报不是一种不好的做法或反模式吗?
    • 如果是服务,您可以删除带有错误消息的 promise resolve/reject。更新了代码。
    • 此解决方案的问题是,我无法处理页面中的承诺拒绝...即使我使用错误块和捕获块,它也会显示未处理的承诺拒绝。有什么想法吗?
    • 您无法使用 try/catch 处理。 promise.then(function(result) { console.log("Promise working"); }, function(err) { console.log("Something broken"); });
    • 我在我的页面中这样处理它:this.printService.print(printData).then((data)=>{ console.log("print hotov"); }, err=>{ console.log(err); this.showAlert(err.message); });即使这样也无法处理
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2011-08-27
    • 2017-12-05
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多