google / google/go-jsonnet

VM errors are obfuscated and incomaptible with `errors.Is|As()`

Open
#592 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
1.8k
Forks
263
PR merge metrics
No merged PRs in 30d

Description

First of all, thank you for this great library. We use JsonNet extensively at https://github.com/ory !

In the current error processing, internal errors are (intentionally?) obfuscated from the caller:

https://github.com/google/go-jsonnet/blob/fb6c700f29d1bcc6b0be96f042670094c69a7001/vm.go#L315

Even if I were to write my own formatter, it would not be possible to pass any additional context without resorting to regexp as the error formater returns a string:

https://github.com/google/go-jsonnet/blob/fb6c700f29d1bcc6b0be96f042670094c69a7001/error_formatter.go#L31

This effectively renders both stdlib functions `errors.Is` and `errors.As` useless as one has to resort to string parsing to identify what error happened. This in particular is difficult if we want to deal with jsonnet errors in our go code. Compare:

```go
_, err := vm.EvaluateAnonymousSnippet(...)
if err != nil {
if strings.Contains(err.Error(), "RUNTIME ERROR: my error") {
// ...
}
return err
}
```

with the more idiomatic:

```go
_, err := vm.EvaluateAnonymousSnippet(...)
if err != nil {
var e *jsonnet.RuntimeError
if errors.As(err, &e); e.Msg == "my error" {
// ...
}
return err
}
```

I understand that the current API makes this a bit difficult as the error formater is a public interface which returns a string, but I think we could improve this with either a flag for the VM (e.g. `IdiomaticErrors bool`):

```patch
if err != nil {
+ if vm.IdiomaticErrors {
+ return "", err
+ }
return "", errors.New(vm.ErrorFormatter.Format(err))
}
```

WDYT?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.