module PipeRpc class Hub class Message def initialize(hub, body) @hub = hub @body = body end def request? @body.has_key? :method end def response? (@body.has_key? :error or @body.has_key? :result) and !!@body[:id] end def error? @body.has_key? :error and @body[:id].nil? end def handle if response? guarded{ handler.handle if handler } else handler.handle if handler end end private def handler_type if request? Hub::Request elsif response? Client::Request::Response elsif error? Message::ErrorResponse else raise 'no request, result or error' end end def handler @handler ||= guarded{ handler_type.new(@hub, @body) } end def guarded yield rescue => e @hub.socket.write PipeRpc::ErrorResponse.new(id: @body[:id], error: { code: -32600, data: { message: e.message } }) nil end end end end