Home > Enterprise >  Function does not continue after catch
Function does not continue after catch

Time:12-07

I have a try..catch within a dart function. When the await client.post throws an error, it does not continue after the catch, why?

  @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);
  }

CodePudding user response:

And it shouldnt. In the code below the catch, you are relying on the response object being set. If the post errors, that wont be the case, producing more errors. Move the log and the return call inside the try block.

CodePudding user response:

The function will not execute after the catch block, the function will be terminated after the catch whenever any exception occurred then the catch block gets called. To solve this issue you can try this.

@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;
  }
}
  • Related