我一直在开发一个涉及前端调用区块链链码的应用程序。
Chaincode为发送的所有事务返回OK消息。即使失败的交易也可以作为回复。虽然可以在区块链日志中看到错误。
有没有办法让链码一直发送错误信息回到前端,以防错误发生,以便前端知道交易是否成功?
答案 0 :(得分:2)
Chaincode应符合以下API:
// Chaincode interface must be implemented by all chaincodes. The fabric runs
// the transactions by calling these functions as specified.
type Chaincode interface {
// Init is called during Instantiate transaction after the chaincode container
// has been established for the first time, allowing the chaincode to
// initialize its internal data
Init(stub ChaincodeStubInterface) pb.Response
// Invoke is called to update or query the ledger in a proposal transaction.
// Updated state variables are not committed to the ledger until the
// transaction is committed.
Invoke(stub ChaincodeStubInterface) pb.Response
}
pb.Response
的位置:
// A response with a representation similar to an HTTP response that can
// be used within another message.
type Response struct {
// A status code that should follow the HTTP status codes.
Status int32 `protobuf:"varint,1,opt,name=status" json:"status,omitempty"`
// A message associated with the response code.
Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"`
// A payload that can be used to include metadata with this response.
Payload []byte `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"`
}
Chaincode shim提供Facade函数来返回response.go中定义的错误和成功状态。因此,在您的链代码上实现流程时,您可以使用不同的响应类型来发送信号并将错误转发回客户端,example:
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
fmt.Println("ex02 Invoke")
function, args := stub.GetFunctionAndParameters()
if function == "invoke" {
// Make payment of X units from A to B
return t.invoke(stub, args)
} else if function == "delete" {
// Deletes an entity from its state
return t.delete(stub, args)
} else if function == "query" {
// the old "Query" is now implemtned in invoke
return t.query(stub, args)
}
return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")
}
如果您尝试调用设置了错误参数的链码,则会回复错误。稍后您可以检查响应以查看是否发生错误或者没有发生错误,您也可以使用消息扩展您的响应,以提供有关所发生情况的更多详细信息。