| @@ -190,6 +190,25 @@ pub fn errorMessage(err: BridgeError) []const u8 { |
| 190 | 190 | }; |
| 191 | 191 | } |
| 192 | 192 | |
| 193 | +/// Narrow the wider error set inferred for a bridge handler to the failures |
| 194 | +/// the dispatcher exposes. Errors the protocol cannot name become the honest |
| 195 | +/// catch-all instead of leaving the page without a reply. |
| 196 | +pub fn fromHandlerError(err: anyerror) BridgeError { |
| 197 | + return switch (err) { |
| 198 | + error.AllocationFailed, error.OutOfMemory => BridgeError.AllocationFailed, |
| 199 | + error.UnknownAction => BridgeError.UnknownAction, |
| 200 | + error.MissingData => BridgeError.MissingData, |
| 201 | + error.InvalidJSON => BridgeError.InvalidJSON, |
| 202 | + error.InvalidParameter => BridgeError.InvalidParameter, |
| 203 | + error.Busy => BridgeError.Busy, |
| 204 | + error.PlatformNotSupported, error.UnsupportedPlatform => BridgeError.PlatformNotSupported, |
| 205 | + error.NotFound => BridgeError.NotFound, |
| 206 | + error.PermissionDenied => BridgeError.PermissionDenied, |
| 207 | + error.Timeout => BridgeError.Timeout, |
| 208 | + else => BridgeError.NativeCallFailed, |
| 209 | + }; |
| 210 | +} |
| 211 | + |
| 193 | 212 | /// Send error to JavaScript via eval |
| 194 | 213 | pub fn sendErrorToJS(allocator: std.mem.Allocator, action: []const u8, err: BridgeError) void { |
| 195 | 214 | var ctx = ErrorContext.init(err, action, errorMessage(err)); |
| @@ -358,6 +377,14 @@ test "errorCodeString returns correct codes" { |
| 358 | 377 | try testing.expectEqualStrings("BUSY", errorCodeString(BridgeError.Busy)); |
| 359 | 378 | } |
| 360 | 379 | |
| 380 | +test "handler error narrowing preserves protocol errors" { |
| 381 | + const testing = std.testing; |
| 382 | + try testing.expectEqual(BridgeError.Busy, fromHandlerError(error.Busy)); |
| 383 | + try testing.expectEqual(BridgeError.PlatformNotSupported, fromHandlerError(error.UnsupportedPlatform)); |
| 384 | + try testing.expectEqual(BridgeError.AllocationFailed, fromHandlerError(error.OutOfMemory)); |
| 385 | + try testing.expectEqual(BridgeError.NativeCallFailed, fromHandlerError(error.NotInTheProtocol)); |
| 386 | +} |
| 387 | + |
| 361 | 388 | test "ErrorContext.toJSON produces valid JSON" { |
| 362 | 389 | const testing = std.testing; |
| 363 | 390 | const allocator = testing.allocator; |