【问题标题】:Flutter how to handle errors in async / awaitFlutter 如何处理异步/等待中的错误
【发布时间】:2020-06-29 21:25:58
【问题描述】:

如果应用程序无法连接到服务器(例如,如果服务器已关闭),我想捕获一个异常,但不确定如何并且到目前为止没有成功。

我的代码:

static Future<String> communicate(String img, String size) async
{    
    String request = size.padLeft(10, '0') + img;
    Socket _socket;

    await Socket.connect(ip, 9933).then((Socket sock) 
    {
        _socket = sock;
    }).then((_)
    {
        //Send to server
        _socket.add(ascii.encode(request));
        return _socket.first;
    }).then((data)
    {
        //Get answer from server
        response =  ascii.decode(base64.decode(new String.fromCharCodes(data).trim()));
    });
    return response;    
}

函数调用:

var ans = await communicate(bs64Image, size);

【问题讨论】:

    标签: flutter dart asynchronous error-handling async-await


    【解决方案1】:

    一般来说,您可以使用 async/await 处理此类错误:

    try { 
       // code that might throw an exception 
    }  
    on Exception1 { 
       // exception handling code 
    }  
    catch Exception2 { 
       //  exception handling 
    }  
    finally { 
       // code that should always execute; irrespective of the exception 
    }
    

    在您的情况下,您应该尝试以下操作:

    try {
       var ans = await communicate(bs64Image, size);
    }
    catch (e){
       print(e.error);
    }
    finally {
    print("finished with exceptions");
    }
    

    【讨论】:

    • 用户 @Vicky Salunkhe 对于 SocketExceptions 是正确的。我的回答是针对一般错误。
    • 您也应该支持@Vicky Salunkhes 的回答。它是特定于 Socketexceptions 的。
    【解决方案2】:

    尝试使用SocketException,如果请求失败会抛出异常

    import 'dart:io';
    
    try {
      response = await get(url);
    } on SocketException catch (e) {
      return e;
    }
    

    【讨论】:

      【解决方案3】:

      要处理异步函数中的错误,请使用 try-catch:

      在异步函数中,您可以像在同步代码中一样编写try-catch clauses

      运行以下示例以查看如何处理来自 asynchronous 函数的错误

      Future<void> printOrderMessage() async {
        try {
          var order = await fetchUserOrder();
          print('Awaiting user order...');
          print(order);
        } catch (err) {
          print('Caught error: $err');
        }
      }
      
      Future<String> fetchUserOrder() {
        // Imagine that this function is more complex.
        var str = Future.delayed(
            Duration(seconds: 4),
            () => throw 'Cannot locate user order');
        return str;
      }
      
      Future<void> main() async {
        await printOrderMessage();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-07-29
        • 2021-09-18
        • 2022-01-09
        • 2018-04-06
        • 2018-11-12
        • 1970-01-01
        • 2017-05-25
        • 1970-01-01
        • 2020-05-24
        相关资源
        最近更新 更多