Sub topic 9
Reporting errors back to Dart
This chapter assumes you can already declare a HostApi, implement it in Kotlin and Swift, and register it, as shown in earlier chapters. Here you will learn what happens when the native side fails, how that failure reaches Dart, and how to design an API so callers can handle it.
What an error looks like on the Dart side
A generated Dart method returns a Future. When the native side reports a failure, the Future completes with a PlatformException. This is the same class that MethodChannel uses. It carries three fields:
| Field | Type | Meaning |
|---|---|---|
| `code` | `String` | A short machine-readable identifier, such as `unavailable` |
| `message` | `String?` | A human-readable description |
| `details` | `Object?` | Extra data of any type the codec supports |
Pigeon does not give you a typed exception hierarchy. The types in the schema are checked, but the error is still a code, a message and untyped details. Treat the code strings as part of your API contract and document them.
Throwing errors from Kotlin
Pigeon generates a Kotlin error class in the output file. In many versions it is called FlutterError. Newer versions may name it after the input file. Open your generated Messages.g.kt and check the name. It holds a code, a message and details.
If your implementation throws this class, the generated handler copies its three fields into the reply, and Dart receives them unchanged.
import android.content.Context
import android.os.BatteryManager
class BatteryApiImpl(private val context: Context) : BatteryApi {
override fun getBatteryInfo(): BatteryInfo {
val manager = context.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
?: throw FlutterError(
"unavailable",
"The battery service is not available on this device.",
null
)
val level = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
if (level <= 0) {
throw FlutterError(
"invalid-level",
"The system reported a battery level of $level.",
mapOf("level" to level)
)
}
return BatteryInfo(level = level.toLong(), state = BatteryState.UNKNOWN)
}
}The details value must be a type the standard codec can encode. A Map of strings to numbers works. A custom Kotlin object does not.
Unexpected exceptions
Suppose your code throws something other than the generated error class, such as an IllegalStateException. The generated handler still catches it. It builds a reply from the exception's class name and its string form, and it adds the cause and stack trace in details. Dart still gets a PlatformException, but its code is something like IllegalStateException. That is useful for debugging and poor as a contract. Callers cannot reasonably switch on it. Throw the generated error class for failures you expect, and leave the automatic wrapping as a safety net.
Throwing errors from Swift
Swift host methods are declared with throws, so you throw an error and the generated handler converts it. Recent Pigeon versions generate a PigeonError struct with code, message and details. Older versions used FlutterError for the same purpose. Check Messages.g.swift for the type your version generated.
import Flutter
import UIKit
class BatteryApiImpl: BatteryApi {
func getBatteryInfo() throws -> BatteryInfo {
UIDevice.current.isBatteryMonitoringEnabled = true
let rawLevel = UIDevice.current.batteryLevel
if rawLevel < 0 {
throw PigeonError(
code: "unavailable",
message: "Battery level is unknown. This is common on the iOS simulator.",
details: nil
)
}
return BatteryInfo(level: Int64(rawLevel * 100), state: .unknown)
}
}UIDevice.batteryLevel returns -1 when monitoring is off or the level is unknown. The earlier version of this example used max(..., 0), which hid that state and reported 0%. Reporting it as an error is more honest.
A plain Swift Error that is not the generated type is also wrapped. The reply then uses a code and message derived from the error's description and type.
What native code cannot report
Some failures never reach Dart because they are not catchable errors:
- A Swift force-unwrap of
nilor an out-of-range array index crashes the app. - An Objective-C
NSExceptionraised inside a Swift handler is not caught by Swift'sdo/catch. It terminates the process. - A Kotlin
OutOfMemoryErroror a crash on a background thread you started yourself bypasses the handler.
Validate inputs and use safe calls (as?, guard let) so that the failures you can predict become errors you can report.
Errors in async methods
For methods marked @async in the schema, the generated native interface has no return value or throws. It receives a callback. You report failure by passing a failure result into that callback, and you must do it exactly once.
In Kotlin the callback takes a Result:
override fun fetchStatus(callback: (Result<BatteryInfo>) -> Unit) {
// Called from any thread. Reply once.
callback(Result.failure(FlutterError("timeout", "No reading within 2 seconds.", null)))
}In Swift the completion takes a Result as well:
func fetchStatus(completion: @escaping (Result<BatteryInfo, Error>) -> Void) {
completion(.failure(PigeonError(code: "timeout", message: "No reading within 2 seconds.", details: nil)))
}Catching errors in Dart
Catch PlatformException where you can do something useful, and convert it into your own domain type close to the boundary. Then the rest of your app does not depend on platform-specific codes.
import 'package:flutter/services.dart';
import 'src/messages.g.dart';
sealed class BatteryResult {
const BatteryResult();
}
class BatteryOk extends BatteryResult {
const BatteryOk(this.info);
final BatteryInfo info;
}
class BatteryUnavailable extends BatteryResult {
const BatteryUnavailable(this.reason);
final String reason;
}
class BatteryRepository {
BatteryRepository({BatteryApi? api}) : _api = api ?? BatteryApi();
final BatteryApi _api;
Future<BatteryResult> read() async {
try {
return BatteryOk(await _api.getBatteryInfo());
} on PlatformException catch (e) {
switch (e.code) {
case 'unavailable':
case 'invalid-level':
return BatteryUnavailable(e.message ?? e.code);
default:
rethrow;
}
}
}
}The default: rethrow branch matters. It lets codes you did not plan for, including the wrapped unexpected exceptions, surface in your error reporting instead of being silently turned into "unavailable".
Errors Pigeon raises for you
Two PlatformException codes come from generated Dart code, not from your native implementation:
| Code | When it happens | Usual cause |
|---|---|---|
| `channel-error` | The call gets no handler on the native side | `setUp` was never called, was called on the wrong messenger, or the plugin is not registered in a background engine |
| `null-error` | The native side returned `null` for a non-nullable result | The schema says `BatteryInfo` but the implementation sent nothing |
channel-error is the most common error in a new Pigeon setup. If you see it, check that registration code runs for the engine that Dart is using. Add the registration to configureFlutterEngine on Android, and to the place where the FlutterViewController or plugin registrar is available on iOS.
Errors in FlutterApi calls
The direction reverses for a FlutterApi. Your Dart implementation may throw. Throwing a PlatformException sends its code, message and details to the native caller. Any other exception is wrapped, with the exception's string form as the message. The native side receives a failure in the completion callback, for example Result.failure(...) in Kotlin. A native call to onBatteryChanged must therefore check its result, or the failure is lost. Dart handlers for a FlutterApi should still catch the errors they expect, so a bug in your Dart code does not turn into noise on the native side.
Designing for failure
Exceptions suit unexpected or exceptional conditions. They are a poor fit when failure is a normal outcome. Consider these options:
- Nullable return type. Declare
BatteryInfo? getBatteryInfo();when "no value" is a normal answer. Dart getsnulland there is no exception. - Result data class. Declare a class with a nullable
valueand a nullableerrorCode. It is more verbose but keeps the failure in the typed schema. Pigeon's data classes are plain, so you check the fields yourself. - Exceptions with documented codes. Use these for real faults such as missing permissions or hardware errors. List each code in the schema's doc comments.
Pigeon's schema language limits how much failure you can model. Older versions cannot express sealed class hierarchies, so a typed union of success and failure is not available there. Check the supported-types notes for your version before relying on one.
Whatever you choose, apply it consistently. If half your methods return null on failure and half throw, every caller must remember which is which.
Common mistakes
- Putting secrets or full stack traces in
message. The message may end up in logs or crash reports. Keep detailed diagnostics indetailsand send only what you need. - Matching on
messagetext. Messages are for people and may change. Match oncode. - Swallowing
channel-error. It indicates a setup bug. Catching it and returning a default hides the real problem. - Throwing from a background thread without replying. In
@asyncmethods, an exception on a thread you started never reaches the handler. Catch it and call the callback with a failure. - Sending non-encodable
details. A custom object indetailsfails to encode, which produces its own error instead of the one you meant to report.
Exercise
A Dart call to getBatteryInfo() throws a PlatformException with code IllegalStateException. Your Kotlin implementation never mentions that code. What happened, and how do you turn it into a code that callers can rely on?
Show answer
Your Kotlin code threw an exception that was not the generated Pigeon error class. The generated handler caught it and wrapped it, using the exception's class name as the code. To give callers a stable code, catch the exception in the implementation, or check the condition beforehand, and throw the generated error (FlutterError in many versions) with your own code, such as invalid-state. Document that code in the schema.
Exercise
You mark fetchStatus as @async in Kotlin. Inside it you start a background thread, and the thread throws an exception before it calls the callback. What does the Dart caller see, and how do you fix it?
Show answer
The Dart Future never completes, because the exception is thrown on a thread that the generated handler does not control, and the callback is never called. Fix it by wrapping the thread's work in try/catch and calling callback(Result.failure(FlutterError(...))) in the catch branch, so every path replies exactly once.
Exercise
Dart code calls a generated API in a new app and gets a PlatformException with code channel-error. Name two likely causes.
Show answer
The native setUp call was never executed, or it ran against a different binary messenger than the engine that Dart is using. For example, registration may be missing in configureFlutterEngine on Android or in the iOS view controller setup, or the code runs in a background engine that has no registration.