简体   繁体   中英

How can you handle dart exceptions that have been declared in a library?

Trying to handle an exception in code below:


  findLocation() async {
    final GoogleMapController controller = await _controller.future;

    try {
      gcd.locationFromAddress(userAddress).then((result) => controller
          .animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
              target: LatLng(result[0].latitude, result[0].longitude),
              zoom: 15))));
    } on gcd.NoResultFoundException {
      print("test");
    }
  }

However, when this block runs unsuccessfully, it produces this error:

NoResultFoundException (Could not find any result for the supplied address or coordinates.)

The error points to this code block:

    switch (platformException.code) {
      case 'NOT_FOUND':
        throw NoResultFoundException();
    }
  }

NoResultFoundException is defined in a class with contents:

/// a [Placemark] from coordinates as [double] latitude and longitude
/// or [Location] from address as [String]
class NoResultFoundException implements Exception {
  /// Constructs the [LocationServiceDisabledException]
  const NoResultFoundException();

  @override
  String toString() =>
      'Could not find any result for the supplied address or coordinates.';
}

How can I handle this error in my findLocation() function? (This is the flutter geocoding library by the way, and the exception is defined in the library files.)

You will only get exceptions if you await your call properly.

If you insist on using a then here, then you will need to use .catchError instead of a traditional try/catch block.

A word of advice, don't mix await and then . It's possible, but it's very easy to make mistakes. Stick with one, probably await , since it's easier to handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM