Skip to content

Commit f572274

Browse files
davidmartos96pchampio
authored andcommitted
Custom error codes on the plugin side (#238)
Custom error codes on the plugin side
1 parent 85ef22c commit f572274

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

plugin/method-channel.go

+32-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,16 @@ func (m *MethodChannel) handleMethodCall(handler MethodHandler, methodName strin
210210
reply, err := handler.HandleMethod(methodArgs)
211211
if err != nil {
212212
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)
214223
if err != nil {
215224
fmt.Printf("go-flutter: failed to encode error envelope for method '%s' on channel '%s', error: %v\n", methodName, m.channelName, err)
216225
}
@@ -223,3 +232,25 @@ func (m *MethodChannel) handleMethodCall(handler MethodHandler, methodName strin
223232
}
224233
responseSender.Send(binaryReply)
225234
}
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

Comments
 (0)