Skip to content

Custom error codes on the plugin side #238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 22, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion plugin/method-channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,16 @@ func (m *MethodChannel) handleMethodCall(handler MethodHandler, methodName strin
reply, err := handler.HandleMethod(methodArgs)
if err != nil {
fmt.Printf("go-flutter: handler for method '%s' on channel '%s' returned an error: %v\n", methodName, m.channelName, err)
binaryReply, err := m.methodCodec.EncodeErrorEnvelope("error", err.Error(), nil)

var errorCode string
switch t := err.(type) {
case *Error:
errorCode = t.code
default:
errorCode = "error"
}

binaryReply, err := m.methodCodec.EncodeErrorEnvelope(errorCode, err.Error(), nil)
if err != nil {
fmt.Printf("go-flutter: failed to encode error envelope for method '%s' on channel '%s', error: %v\n", methodName, m.channelName, err)
}
Expand All @@ -223,3 +232,25 @@ func (m *MethodChannel) handleMethodCall(handler MethodHandler, methodName strin
}
responseSender.Send(binaryReply)
}

// Error implement the Go error interface, can be thrown from a go-flutter
// method channel plugin to return custom error codes.
// Normal Go error can also be used, the error code will default to "error".
type Error struct {
err string
code string
}

// Error is needed to comply with the Golang error interface.
func (e *Error) Error() string {
return e.err
}

// NewError create an error with an specific error code.
func NewError(code string, err error) *Error {
pe := &Error{
code: code,
err: err.Error(),
}
return pe
}