@@ -210,7 +210,16 @@ func (m *MethodChannel) handleMethodCall(handler MethodHandler, methodName strin
210
210
reply , err := handler .HandleMethod (methodArgs )
211
211
if err != nil {
212
212
fmt .Printf ("go-flutter: handler for method '%s' on channel '%s' returned an error: %v\n " , methodName , m .channelName , err )
213
- binaryReply , err := m .methodCodec .EncodeErrorEnvelope ("error" , err .Error (), nil )
213
+
214
+ var errorCode string
215
+ switch t := err .(type ) {
216
+ case * Error :
217
+ errorCode = t .code
218
+ default :
219
+ errorCode = "error"
220
+ }
221
+
222
+ binaryReply , err := m .methodCodec .EncodeErrorEnvelope (errorCode , err .Error (), nil )
214
223
if err != nil {
215
224
fmt .Printf ("go-flutter: failed to encode error envelope for method '%s' on channel '%s', error: %v\n " , methodName , m .channelName , err )
216
225
}
@@ -223,3 +232,25 @@ func (m *MethodChannel) handleMethodCall(handler MethodHandler, methodName strin
223
232
}
224
233
responseSender .Send (binaryReply )
225
234
}
235
+
236
+ // Error implement the Go error interface, can be thrown from a go-flutter
237
+ // method channel plugin to return custom error codes.
238
+ // Normal Go error can also be used, the error code will default to "error".
239
+ type Error struct {
240
+ err string
241
+ code string
242
+ }
243
+
244
+ // Error is needed to comply with the Golang error interface.
245
+ func (e * Error ) Error () string {
246
+ return e .err
247
+ }
248
+
249
+ // NewError create an error with an specific error code.
250
+ func NewError (code string , err error ) * Error {
251
+ pe := & Error {
252
+ code : code ,
253
+ err : err .Error (),
254
+ }
255
+ return pe
256
+ }
0 commit comments