Sub topic 8
Reporting errors from native code to Dart
This chapter assumes you have the battery_info plugin from the earlier chapters. That means a working MethodChannel named battery_info, a Kotlin onMethodCall, and a Swift handle method. It also assumes you are comfortable with try/catch in Dart, Kotlin and Swift. Here you will decide what each failure looks like on the Dart side and make both platforms report failures the same way.
Three outcomes of every call
A method call over a platform channel ends in exactly one of three ways. The native handler must choose one, and the Dart side must be ready for all three.
| Native action | Android | iOS | What Dart sees |
|---|---|---|---|
| Success | `result.success(value)` | `result(value)` | The `Future` completes with the value |
| Error | `result.error(code, message, details)` | `result(FlutterError(...))` | The `Future` throws `PlatformException` |
| Unknown method | `result.notImplemented()` | `result(FlutterMethodNotImplemented)` | The `Future` throws `MissingPluginException` |
A PlatformException carries three fields:
codeis a short string. It is the only field callers should branch on.messageis human-readable text and may be null.detailsis any value the standard message codec can carry, for example a string, a number or a map.
Choosing error codes
Error codes are part of your plugin's public contract, even though the channel is private. Apps will end up depending on them. Follow these rules:
- Use the same code strings on Android and iOS for the same situation. If one platform says
UNAVAILABLEand the other saysNOT_AVAILABLE, callers need platform checks. - Use upper-case snake case, such as
UNAVAILABLEorPERMISSION_DENIED, and keep the codes stable between releases. - Put the explanation in
messageand any extra data indetails. Do not encode data in the code, as inERROR_42. - Document each code in the doc comment of the Dart method that can throw it.
Reporting errors on Android
The plugin from the previous chapters already reports UNAVAILABLE. A real handler also has to deal with exceptions thrown by the platform API itself. If an exception escapes onMethodCall, the engine logs it and replies with no usable value. Your Dart code then sees a null result with no explanation. Catch exceptions in the handler and turn them into an error reply:
override fun onMethodCall(call: MethodCall, result: Result) {
when (call.method) {
"getBatteryLevel" -> {
try {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level >= 0) {
result.success(level)
} else {
result.error("UNAVAILABLE", "Battery level not available.", null)
}
} catch (e: SecurityException) {
result.error("PERMISSION_DENIED", e.message, null)
} catch (e: Exception) {
result.error("NATIVE_FAILURE", e.message, e.javaClass.name)
}
}
else -> result.notImplemented()
}
}Catch the specific exceptions you can name first, then add one broad catch as a safety net. The class name in details helps you debug a failure without a debugger attached.
Reporting errors on iOS
Swift has no equivalent of an uncaught Kotlin exception that the engine can intercept. A crash inside handle takes down the whole app. Be careful with force unwraps (!) and forced casts (as!), especially when reading arguments.
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getBatteryLevel":
UIDevice.current.isBatteryMonitoringEnabled = true
let level = UIDevice.current.batteryLevel
if level < 0 {
result(FlutterError(code: "UNAVAILABLE",
message: "Battery level not available.",
details: nil))
} else {
result(Int(level * 100))
}
default:
result(FlutterMethodNotImplemented)
}
}When a native call throws a Swift Error, catch it with do/catch and convert it to a FlutterError, using the same code strings as the Kotlin side. For arguments, use a guard that returns a FlutterError with code INVALID_ARGUMENT instead of force-casting.
Converting to a plugin-specific exception
Callers of your package should not need to import flutter/services.dart just to catch errors. They also should not need to know that a channel exists. Wrap PlatformException in your own type. Add a typed kind so callers can use a switch instead of comparing strings:
import 'package:flutter/services.dart';
enum BatteryInfoErrorKind { unavailable, permissionDenied, unsupported, unknown }
class BatteryInfoException implements Exception {
BatteryInfoException(this.code, this.message, {this.details});
final String code;
final String? message;
final Object? details;
BatteryInfoErrorKind get kind => switch (code) {
'UNAVAILABLE' => BatteryInfoErrorKind.unavailable,
'PERMISSION_DENIED' => BatteryInfoErrorKind.permissionDenied,
'UNSUPPORTED' => BatteryInfoErrorKind.unsupported,
_ => BatteryInfoErrorKind.unknown,
};
@override
String toString() => 'BatteryInfoException($code, $message)';
}
class BatteryInfo {
static const MethodChannel _channel = MethodChannel('battery_info');
/// Returns the battery level as a percentage from 0 to 100.
///
/// Throws [BatteryInfoException] with kind
/// [BatteryInfoErrorKind.unavailable] when the platform cannot report
/// a level, for example on some emulators.
Future<int> getBatteryLevel() async {
try {
final int? level = await _channel.invokeMethod<int>('getBatteryLevel');
if (level == null) {
throw BatteryInfoException('NULL_RESULT', 'The platform returned no value.');
}
return level;
} on PlatformException catch (e) {
throw BatteryInfoException(e.code, e.message, details: e.details);
} on MissingPluginException {
throw BatteryInfoException('UNSUPPORTED', 'Not implemented on this platform.');
}
}
}Three details in this code matter:
invokeMethod<int>returnsint?. Replacing the earlierlevel!with an explicit null check turns a confusingNull check operatorerror into a clear plugin exception.MissingPluginExceptionis a separate class. It is not aPlatformException, so it needs its ownonclause. It appears when the method name is unknown to the native side. It also appears when the plugin is not registered on the current platform, such as on web or desktop, or in a unit test that has no mock handler.- The
BatteryInfoExceptionthrown inside thetryblock is not caught by theonclauses below it, because it matches neither type.
Common mistakes
- Mismatched codes. Android sends
UNAVAILABLEand iOS sendsNOT_AVAILABLE. Fix it by defining the codes once, in a table in your documentation, and checking both sides against it. - Unsupported detail types.
detailsgoes through the standard codec. Passing a KotlinExceptionobject or a SwiftErrorfails to encode. Sende.toString()or a map of strings instead. - Swallowed errors. An empty
catchblock that never replies leaves the Dart caller waiting forever. - Branching on
message. The text may change between releases or be localized by the OS. Branch only oncode. - Treating
MissingPluginExceptionas a native failure. It usually points to a registration or naming problem. Check that the channel name and method string match on all three sides.
Exercise
A teammate's getBatteryLevel hangs forever on iOS when the battery level is unknown, but returns an error on Android. The Swift code is: if level >= 0 { result(Int(level * 100)) }. What is wrong, and what should the Dart caller see after you fix it?
Show answer
The Swift handler has no reply on the level < 0 path, so the Dart Future never completes. Add an else branch that calls result(FlutterError(code: "UNAVAILABLE", message: "Battery level not available.", details: nil)). The Dart invokeMethod call then throws a PlatformException with code UNAVAILABLE. The plugin wraps it in a BatteryInfoException whose kind is BatteryInfoErrorKind.unavailable, the same as on Android.
Exercise
Why must the Dart code catch MissingPluginException separately from PlatformException?
Show answer
They are unrelated classes, so an on PlatformException clause does not catch MissingPluginException. A MissingPluginException means no native handler answered the method name. This happens when the method is not implemented, or when the plugin is not registered on the current platform. A PlatformException means a handler ran and reported a failure. The two cases usually need different handling, such as reporting "unsupported" versus "try again".