Skip to content

Commit

Permalink
feat: add error awareness to go deserialization (#3793)
Browse files Browse the repository at this point in the history
Adds logic to detect when error responses are returned from the kernel within the go runtime library. This allows us to bubble up the correct error messaging from the kernel instead of just failed deserialization with unexpected response format.

---

By submitting this pull request, I confirm that my contribution is made under the terms of the [Apache 2.0 license].

[Apache 2.0 license]: https://www.apache.org/licenses/LICENSE-2.0
  • Loading branch information
MrArnoldPalmer authored Oct 6, 2022
1 parent dae724c commit 9b6a307
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
4 changes: 1 addition & 3 deletions packages/@jsii/go-runtime-test/project/compliance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1536,15 +1536,13 @@ func (i ImplementsStructReturningDelegate) ReturnStruct() *calc.StructB {
}

func (suite *ComplianceSuite) TestExceptions() {

require := suite.Require()

calc3 := calc.NewCalculator(&calc.CalculatorProps{InitialValue: jsii.Number(20), MaximumValue: jsii.Number(30)})
calc3.Add(jsii.Number(3))
require.Equal(float64(23), *calc3.Value())

// TODO: should assert the actual error here - not working for some reasons
require.Panics(func() {
require.PanicsWithError("Error: Operation 33 exceeded maximum value 30", func() {
calc3.Add(jsii.Number(10))
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package process

import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
Expand All @@ -17,6 +18,12 @@ import (

const JSII_RUNTIME string = "JSII_RUNTIME"

type ErrorResponse struct {
Error string `json:"error"`
Stack *string `json:"stack"`
Name *string `json:"name"`
}

// Process is a simple interface over the child process hosting the
// @jsii/kernel process. It only exposes a very straight-forward
// request/response interface.
Expand Down Expand Up @@ -197,7 +204,31 @@ func (p *Process) readResponse(into interface{}) error {
if !p.responses.More() {
return fmt.Errorf("no response received from child process")
}
return p.responses.Decode(into)

var raw json.RawMessage
var respmap map[string]interface{}
err := p.responses.Decode(&raw)
if err != nil {
return err
}

err = json.Unmarshal(raw, &respmap)
if err != nil {
return err
}

var errResp ErrorResponse
if _, ok := respmap["error"]; ok {
json.Unmarshal(raw, &errResp)

if errResp.Name != nil && *errResp.Name == "@jsii/kernel.Fault" {
return fmt.Errorf("JsiiError: %s", *errResp.Name)
}

return errors.New(errResp.Error)
}

return json.Unmarshal(raw, &into)
}

func (p *Process) Close() {
Expand Down

0 comments on commit 9b6a307

Please sign in to comment.