dart 函数在catch后不继续

hgqdbh6s  于 2022-12-16  发布在  其他
关注(0)|答案(3)|浏览(134)

我在dart函数中有一个try..catch。当await client.post抛出错误时,它在catch之后没有继续,为什么?

@override
  Future<http.Response> post(url, {Map<String, String?>? headers, body, Encoding? encoding, BuildContext? context}) async {
    headers = await prepareHeaders(headers);

    http.Response? response = null;
    try {
      response = await client.post(url, headers: headers as Map<String, String>?, body: body, encoding: encoding);
    } catch (_) {
      debugPrint('test'); // It comes here        
    }
    // Does not come here

   log(url: url, type: 'POST', body: body as String?, response: response!);
   return await parse(response, context: context);
  }
eufgjt7s

eufgjt7s1#

它不应该这样做。在catch下面的代码中,你依赖于正在设置的响应对象。如果post错误,那就不是这样了,会产生更多的错误。将log和return调用移到try块中。

k5ifujac

k5ifujac2#

您的代码几乎可以肯定在catch代码块之后继续;如果client.post抛出了一个异常,那么response将不会被设置,并且将保留它的初始值null。但是,在catch块之后,您需要:

log(url: url, type: 'POST', body: body as String?, response: response!);

它Assertresponse不是null。这将抛出TypeError
我不知道您为什么没有观察到TypeError,但我怀疑您在调用堆栈中的某个较高位置有一个覆盖catch块,它正在吞噬异常(特别是考虑到您在所显示的代码中使用了catch (_))。

  • 避免没有oncatch
  • 未捕获Error
wnrlj8wa

wnrlj8wa3#

函数在catch块之后将不会执行,函数将在catch之后终止,无论何时发生异常,然后调用catch块。要解决此问题,您可以尝试以下操作。

@override
Future<http.Response> post(url, {Map<String, String?>? headers, body, 
Encoding? encoding, BuildContext? context}) async {
headers = await prepareHeaders(headers);

http.Response? response = null;
try {
  response = await client.post(url, headers: headers as Map<String, 
  String>?, body: body, encoding: encoding);
log(url: url, type: 'POST', body: body as String?, response: response!);
return await parse(response, context: context);
 } catch (_) {
  debugPrint('test');
  rethrow;
  }
}

相关问题