Repository navigation
Description
Summary
Use GraphQL’s error extensions field to add extra information that can be used by the SDKs to raise different exceptions or error types to users. This removes the need to parse the error message for extracting exitCode, stdout and stderr.
Background
GraphQL services may provide an additional entry to errors with key
extensions. This entry, if set, must have a map as its value. This entry is reserved for implementors to add additional information to errors however they see fit, and there are no additional restrictions on its contents.
- GraphQL spec: Error result format
Motivation
Not all errors are the same. Some are expected (e.g., lint command that failed validation), others are unexpected (e.g. network down). Having different error types allows greater control over some failure conditions if needed. It’s also useful to add extra context.
The biggest example of this are errors from exec operations.
Unexpected errors
When making queries (i.e., sending request to engine) all returned errors look the same, but when running commands, you can parse the error message to look for clues. If the error message doesn’t contain exit code: then the command wasn’t even executed. This could be due to a killed engine process for example.
try:
await ctr.exit_code()
except dagger.QueryError as e:
if "exit code:" in str(e):
return False
# no exit code means it's an unexpected failure,
# so bubble the exception up
raise
return TrueThe main problem here is users having to parse the error message. It would be much better to be able to catch different exceptions for these cases:
try:
await ctr.exit_code()
except dagger.ExecError:
return False
return TrueSame thing. Uncaught exception bubbles up.
Getting exitCode, stdout and stderr
Some users need the actual value of exitCode, stdout and stderr when a command fails. While in most cases that’s only needed for debugging, there’s also use cases for collecting job statuses for a report, logging, or just for controlling output in a dev tool or webhook that uses dagger underneath.
Having to parse the error message with regex patterns for these values is a workaround.
Example of a user’s code
func normalizeStdoutError(err error) (string, string, int, error) {
result := regexp.MustCompile(`(?s)(.*?)\nStdout:\n(.*?)\nStderr:\n(.*)\n\n`).FindStringSubmatch(err.Error())
if len(result) != 4 {
return "", "", -1, fmt.Errorf("match string: %w", err)
}
errorMsg := result[1]
stdout := result[2]
stderr := result[3]
exitCodes := regexp.MustCompile(`(?s)exit code: (.*)`).FindStringSubmatch(errorMsg)
if len(exitCodes) != 2 {
return "", "", -1, fmt.Errorf("match exitcode: %w", normalizeErr)
}
exitCode, err := strconv.Atoi(exitCodes[1])
if err != nil {
return "", "", -1, fmt.Errorf("atoi: %w", err)
}
return stdout, stderr, exitCode, nil
}With different error types, you could simply access them as attributes instead if needed:
_, err := ctr.ExitCode(ctx)
if exerr, ok := err.(*dagger.ExecError); ok {
return exerr.ExitCode
}Specification
Add an extension entry to the error in the response, with key _type and a pre-established code value for each error type that is supported, along with any extra fields that are needed:
{
"errors": [
{
"extensions": {
"_type": "<CODE>",
"...": "..."
}
}
]
}Engine
Declare the custom errors (that implement gqlerrors.ExtendedError) in a single place to also serve as documentation for the SDKs.
Example implementation
type ErrorCode string
const (
ExecErrorCode ErrorCode = "EXEC_ERROR"
)
type ExecError struct {
original error
Command []string
ExitCode int
Stdout string
Stderr string
}
func (e ExecError) Error() string {
return e.original.Error()
}
func (e ExecError) Unwrap() error {
return e.original
}
func (e ExecError) Extensions() map[string]interface{} {
return map[string]interface{}{
"_type": string(ExecErrorCode),
"command": e.Command,
"exitCode": e.ExitCode,
"stdout": e.Stdout,
"stderr": e.Stderr,
}
}In wrapSolveError (core/gateway.go), replace fmt.Errorf with custom error:
- returnErr = fmt.Errorf("%w\nStdout:\n%s\nStderr:\n%s", returnErr, stdout, stderr)
+ returnErr = ExecError{
+ original: returnErr,
+ Command: execOp.Exec.Meta.Args,
+ ExitCode: exitCode,
+ Stdout: stdout,
+ Stderr: stderr,
+ }This will produce the following example response:
{
"data": null,
"errors": [
{
"message": "process \"sh -c hello\" did not complete successfully: exit code: 127",
"locations": [
{
"line": 1,
"column": 137
}
],
"path": [
"container",
"from",
"withExec",
"stdout"
],
"extensions": {
"_type": "EXEC_ERROR",
"command": ["sh", "-c", "hello"],
"exitCode": 127,
"stdout": "hello",
"stderr": ""
}
}
]
}SDKs
Implement the custom errors as meant to be consumed by users.
Example: Go
type ExecError struct {
original gqlerror.Error
Command []string
ExitCode int
Stdout string
Stderr string
}
func (e ExecError) Error() string {
return e.original.Error()
}
// questionable if needed
func (e ExecError) Debug() string {
return fmt.Sprintf("%v\nStdout:\n%s\nStderr:\n%s\n", e, e.Stdout, e.Stderr)
}
func (e ExecError) Unwrap() error {
return e.original
}When getting a response, check for the value of _type in the error’s extensions field (if exists), and return the custom error:
typ, ok := err.Extensions["_type"].(string)
if typ == "EXEC_ERROR" {
e := ExecError{original: err}
if exitCode, ok := err.Extensions["exitCode"].(int); ok {
e.ExitCode = exitCode
}
if stdout, ok := err.Extensions["stdout"].(string); ok {
e.Stdout = stdout
}
...
}Backwards compatibility
If an SDK doesn’t implement a custom error, it’ll still return the more general error type. The extra fields are simply ignored.
However, specifically for an ExecError, moving stdout and stderr out of the error message into extensions is a breaking change for users that are parsing the error message to extract these fields.
For these users, it’s almost certain that they’ll have a reusable function they’re using for extracting them, so they should only need to adapt in one place, being able to make quite a clean up.
It’s also possible to wrap the custom error in the previous message format when representing as a string to preserve compatibility temporarily, but it’s better to do it in the SDK to keep the API clean.
Rationale
Error codes
Using the extensions field to make custom error types in a GraphQL client is nothing new. The Apollo Server has several built-in error codes like INTERNAL_SERVER_ERROR, that can then handled in the client.
We don’t need to make an exhaustive list right now. Errors like BAD_REQUEST are minimized when using one of our type-safe SDKs. Even though Python’s type-checking is optional and doesn’t execute at runtime (making it quite possible to have validation errors), we can add more error types later when we see a need for it.
GraphQL best practices
It’s a GraphQL best practice to reserve the errors field in the response for unexpected errors like a server issue (5xx HTTP codes) or a validation error (4xx HTTP codes, malformed query, failure in validating types against schema, etc). Basically something that went wrong in servicing the request.
What’s in data can also tell you different things: data exists or not, is null or has the path to a field that is null. This alone can help the client detect different error conditions without relying on extensions.
Generally, the way to handle unexpected errors is to return a friendly error message to the user, while logging the full error from the server for debugging purposes. And for user facing errors (typically meaning there’s nothing wrong processing the request but what’s asked can’t be delivered, e.g., no permissions, not authorized, resource not found, etc), is to model the error in the GraphQL schema and return it in data.
However, our use of GraphQL is very particular because we’re using it to build a lazy pipeline with a structure that matches the nesting in the query, so these things don’t map too well in our use case. For example:
query {
container {
from(address: "alpine") {
withExec(args: ["apk", "add", "curl"]) {
withExec(args: ["curl", "https://dagger.io/"]) {
stdout
}
}
}
}
}When stdout processes the pipeline, an error could occur in the step generated by the first withExec. It’s hard to know what’s an expected vs unexpected error with our API, or where the error comes from. It could be that the Internet connection is down so apk fails to download the package (unexpected), or the command is not found due to a typo (expected, user facing). And both of those errors will have the path container.from.withExec.withExec.stdout instead of container.from.withExec.
Dagger is also a tool for developers, not end users. So it’s simpler to rely on errors for all kinds of errors, use extensions when it makes sense to add extra data to the error, and return the error message as is through to the client.
It’s then the developer’s responsibility to choose what to handle, log and show to the final users.
Activity
[-]Distinguish between different kinds of errors from the API (user vs server error)[/-][+]Proposal: Error types[/+]helderco commentedon May 10, 2023
The original post required a bit of research. I’ve done that and updated the issue with a proposal.
[-]Proposal: Error types[/-][+]Error types[/+]