You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
✨ Enable ability for Dagger functions to return an error and a response #8421
Dagger functions can currently return an error OR any other value but they can't do both at the same time. This makes it impossible to implement pipelines steps that may fail (and ultimately should fail the pipeline), but always yields some report. Typical example: test or lint results.
Similarly to how other CI pipeline steps currently work today, it should be possible to achieve the same behavior in Dagger as doing: ./my_command 2>my_output_report to get the execution status as well as any artifacts that might be generated.
How are you currently working around this?
The only way to go around this limitation is by actually fiddling with the pipeline code and perform this in two dagger calls. One to fetch whatever artifact we need from our pipeline, and the second to actually make the execution fail.
Reacted by Matthias Grandl, Michael Grinshpon and Daniel Wegener
Half baked thought: we actually don't even have a nice way for functions to return errors at the moment.
If you return an error in the Go SDK that just bubbles up into a fmt.Println(os.Stderr, err.Error()) and os.Exit(1) in the runtime entrypoint. which just turns into an ugly error message in the trace, even if you returned a nicely formatted message.
If we changed that to something like function.ReturnError(…) similar to how we register function return values, that might be a building block here.
typeQuery {
# Construct an Error value to be returned by a function.error(message: String!): Error!
}
typeError {
id: ErrorID! # A brief description of the error.message: String!
}
typeFunctionCall {
# Return an error from the function.returnError(error: ErrorID!): Void
}
Quoting for convenience:
Broader question: can we envision building on this to satisfy the "error reports" use case? For example, by supporting multiple errors, or hierarchical errors, or other extensions to the Error type? Or, do we think this is fundamentally off-base and we actually need to support 'arbitrary type + error' returns?
Putting my cards on the table: sticking with "return a value OR an error" seems familiar and conventional to me, so it'd be pretty convenient if every use case that motivated #8421 (lints, tests, ???) neatly fit into a rich Error API. But, that's just my current thinking - I see this more like the start of a beautiful bikeshed. 😄
There's also a lot of inspiration from Go's "errors ARE values" idea here - we could even have *Error satisfy error interface, and whatever else makes sense for other SDKs.
One issue I can forsee if we allow both errors and values returned - this pattern won't fit neatly into every language. For go, where v, err := doThing() is a very common pattern, it's fine, but if an SDK is using exceptions instead (like Python does), then it's not particularly easy to follow the control flow - the function throws an exception, and the value never gets assigned.
I think I prefer @vito's suggestion of rich error types - I really really like the idea of being able to take any module object and wrap it into an error type (not just message strings), which feels quite fun - you could have a rich linting report, with all your structured data, that's now an error. From a codegen POV, this could look a lot like how we have ExecErr today (this would be so cool to visualize in cloud as well).
Although, potential weirdness - we'd essentially have a dynamic/generic error type in the core api. Is that an issue? How would that work? We definitely would need to do some fun extensions to get this.
Ok, so wanting to circle back to this, I actually have a concrete use case in #9356 I'd like to solve. Essentially, making a release now returns a "release report" - some of these operations might have failed.
The whole thing has actually failed - so I would want the dagger call command to exit - but I still need to get the markdown report out as well. Ideally, running dagger call -m releaser publish ... markdown would return the report string on stdout, and also exit 1.
I'd also like to be able to take this even further - suppose the report had an interactive container to play around with the results (e.g. to help debug test failures), then I should be able to do: dagger call -m releaser publish ... container with-mounted-file ... terminal to mount a local tool into the debuggable container! I should be able to manipulate the returned value, even if the command will eventually exit with 1. This could also work with the prior discussed example of a directory of screenshots produced from a failed selium test.
If we just had to consider go, then just return &report, err would be nice, as the original proposal suggests. We could even represent this neatly in the new dagger.Error type. The problem comes when you would put this in Python or Typescript, where such a failure propagates to an exception, as I point out in #8421 (comment).
If we do what I suggest there, and encode all the information into the error type, then we very quickly run into a problem:
What type does this function return? It can actually return a directory or a container! And we can't know which one until runtime (and we either error, or we don't). So doing something like dagger call func with-exec ... may succeed or may fail to find the with-exec step - depending on the error.
So I think we get this important rule - if we attach a value to an error type, then it should be the same type as the function should normally return. And we should have a way to check that this is true.
One option for those languages could be to try the pattern here: https://github.com/castedo/unexceptional - essentially, allow returning errors directly instead of throwing them. If we did this, we could allow for module functions to use a go-like pattern for cases where you should be able to return a value and an error. All function calls to outside functions would still throw exceptions.
if(resinstanceofDaggerError){// We know an error was returned}// ORconst{ res, err }=myFctcall()if(err!==undefined){
...
}
However, this will impact the user DX too, if he call some of its own function internally, he might have some pain dealing with that type of error handling since it's not native to the language.
2. Shadow error type
Maybe a utility function that wrap a result and return an error is preferable in term of DX, and this will just skip the type safety, the DX will be the same for the user, no additional typing, just a utility function to call
Example:
// Utility fct// We put any as return type so it can bypass type safety when an user returns itexportclassDaggerError{constructor(privatereadonlyvalue: any,privatereadonlyerror: Error|string){}}exportfunctiondaggerError(value: any,err: Error|string): any{returnnewDaggerError(v,err)}
@func()asyncdefoneReturn(): Promise<string>{// The user wraps its error into a customreturndaggerError("value","error-message")}
3. Custom Dagger Error with native style
We could even just let the user throw and add a custom error type that we can catch on our side to share both error & value, that could be even better IMO and doesn't disturb the DX.
exportclassDaggerErrorimplementsError{...}
@func()asyncdefoneReturn(): Promise<string>{// The user wraps its error into a customthrownewDaggerError("xx value","xx-errormessage")}
Then internally we catch and check if that's a daggerError, then we look for the value.
I think solution 3 is the best for Typescript but let me know what you guys think
@TomChv I like the last option the most - assuming that's the closest to how errors would normally be used in TypeScript.
Same for Python I figure; each SDK runtime should catch errors/exceptions in the native manner and turn them into rich dagger.Error function return values.
@jedevc Hrm, I don't think we need to worry about conflicting return types - to me, it's not "return type V on success and type E on error", it's "return type V, or return a GraphQL error" - GraphQL errors can come with their own type and fields, so it seems like a potential medium for sending rich errors back.
Errors are tricky: if you try to pre-declare "my function only returns V or an error of type E" - what happens when some unexpected error occurs, i.e. in a module dependency? I think we can't treat this like an Option type; errors are their own thing, and asserting on their type dynamically at runtime is the "thing to do" in basically every language that deals with them. (I do like the type hint of "I intend to return these error types" - but don't really know how to apply it.)
In an ideal world, Error would actually be an interface:
interfaceError {
error: String! # or message, but that seems less likely to intentionally implement `Error`
}
Then, today's Error would instead become StandardError or something, and if you wanted to return a *Container along with your error you would define your own Error type that just has it as a field.
Technically we could keep Error concrete and support attaching arbitrary fields - storing IDs as fields where you want to store an object. This kind of works, since IDs even include their own type with some effort you could determine which loadFooFromID to call to turn it into a real live *Container, but it's not type safe at all and incredibly clunky to work with.
Then, when we're returning an Error from a function, we can send along the concrete type and pre-fetched fields using GraphQL error extensions. The client-side can then turn that into concrete error types known to the module so you can do type switches as normal, or it could return a generic error that preserves the type/fields if the type isn't directly exposed to it.
ExecError would become an actual error type in the API, instead of something special-cased in each SDK.
I'm glossing over the hard bits here for sure, but I think that's what would feel most natural across SDKs.
Getting back to your original use case ("I want to attach to an errored container with terminal") we might need some sort of syntax for "capture an error and continue the chain from it".
So if you ran this, and it failed, we could print the error out nicely:
$ dagger call foo
Error: MyRichContainerError: process exited with status 42
Fields:
container: Container!# bleh, gotta use a character that's not interpreted by the shell, so '!' and '?' are both out
$ dagger call foo ^ container terminal
Or, more ideally, we would pop you into a dagger shell with the error already loaded as the current context:
$ dagger call foo -i
Error: MyRichContainerError: process exited with status 42
Fields:
container: Container!> container | terminal
Getting back to your original use case ("I want to attach to an errored container with terminal") we might need some sort of syntax for "capture an error and continue the chain from it".
So if you ran this, and it failed, we could print the error out nicely
I kinda don't hate the ^ 😆
But, I do think that having some "type" of what the returned value is is important. It's not important for the error to have any specific type, agreed that that could be an interface. But if you can just naturally continue the chain (e.g. getting the report and the error), it would be good to be able to statically type the continued value.
e.g. imagine constructing an ID for something like dagger call foo ^ container. Until you run it, you can't determine if container is a property on the error, or what fields it even has, etc. I guess that's not a limitation for now? But it feels like it reduces the predictability of a command - now as the caller, I need to know how the module author has exactly produced their module to handle error cases (since different branches could return entirely different types to continue on).
😆 regardless, I actually do agree with all your points that we should be able to implement our own Error types - even if we don't support this "strongly-typed" pattern with multiple-returns, etc. Potentially it's possible to even do both 🤔 (e.g. if a a returned Error supports a Continue() T where T is the return type of the function we can allow continuing from that point`).
@MatthiasGrandl Hi! Would you mind providing a few details on your use case?
There's been some progress depending on what you're after. Namely, our Error API type supports having arbitrary named (JSON) values attached to it, which will get propagated back to the client. But it's currently an implementation detail - there are parts missing to make it ergonomic (like being able to return it as a Go error or raise it as a Python exception, etc.).
@vito thanks for the reply! For example I have a job for running integration tests, which on fail returns junit test results that I need to export to get a nice report. Currently I have to workaround it with expect: any to then export the test results and then fail the pipeline afterwards.
This is also affecting our team. Our workaround for tests/linters is to return an error if issues are found, and if users want to view the results they can re-run with an option to return an artifact (string, *dagger.File, or *dagger.Directory).
We considered adding the results to the error itself, but it limits the returned artifacts to a single string. This not only makes it a little troublesome for some linters that output to files, but if we want a module to run many linters in parallel the output becomes large and difficult to parse through.
This significantly hampers adoption of dagger for teams using gitlab - especially since they're the other major game in town after github's most recent rugpull.
dagger.cloud, however, has these lovely red spans that say "yo, this is broken!" A dagger job can emit a result to an external link and then users can click through into the dagger cloud link.
It would be awesome if teams using gitlab could have their cake and eat it, too - see the spans in dagger cloud as being broken AND see reports popping up in PRs.
It's not even like it'd be bad for github users! For example:
Then, in a script, you can do something like this to call out to the dagger engine:
#!/usr/bin/env dagger# Call CI function ONCE and capture the result object# Change `exit-code-test | test-this` to your project's CI function
result=$(exit-code-test | test-this)# Export reports directory to host filesystem# The `result` field contains the dagger.Directory of reports$result| result |export ./reports
# Get exit code and propagate to shell
exit_code=$($result| exit-code)
.exit $exit_code
I will say that making a shell script to call out to dagger to get what I kind of want to get in the first place feels like a violation of what dagger wants to do, but it does work and it's less painful than the medieval torture chamber that is gitlab ci.
If anyone figures out how to let that script have args, let me know, because I have not figured it out.
But seriously, being able to do something like this feels like it'd a huge step in making dagger feel really nice:
importdaggerfromdaggerimportdag@dagger.object_typeclassRuff:
"""Ruff linting and formatting toolchain. A composable toolchain for running ruff lint and format checks. Automatically detects ruff version from the project's uv.lock file. Args: source: The uv project directory containing pyproject.toml and uv.lock. """source: dagger.Directory=dagger.field()
@dagger.functionasyncdeflint_report(self) ->dagger.Result[dagger.File, dagger.File]:
"""Run ruff lint and return GitLab Code Quality report with exit code. Returns both the report file and exit code so CI can: 1. Collect the report as a codequality artifact 2. Fail the build if there are lint errors The report is generated even if lint errors exist. """version=await_get_ruffversion(self.source)
result=await (
_ruff_container(self.source, version)
.with_exec(
[
"ruff",
"check",
"--output-format=gitlab",
"--output-file=/tmp/lint-report.json",
],
expect=dagger.ReturnType.ANY,
)
.sync()
)
exit_code=awaitresult.exit_code()
report_file=result.file("/tmp/lint-report.json")
returndag.success(report_file) ifexit_code==0elsedag.error(report_file)
Then, calls can still exit with an error code yet still emit results without going through the complexities of making bespoke .dagger scripts for each project in a repo:
Activity
vito commentedon Sep 12, 2024
Half baked thought: we actually don't even have a nice way for functions to return errors at the moment.
If you return an error in the Go SDK that just bubbles up into a
fmt.Println(os.Stderr, err.Error())andos.Exit(1)in the runtime entrypoint. which just turns into an ugly error message in the trace, even if you returned a nicely formatted message.If we changed that to something like
function.ReturnError(…)similar to how we register function return values, that might be a building block here.vito commentedon Sep 16, 2024
A bikeshedding opportunity emerges:
MVP API:
Quoting for convenience:
jedevc commentedon Sep 16, 2024
One issue I can forsee if we allow both errors and values returned - this pattern won't fit neatly into every language. For go, where
v, err := doThing()is a very common pattern, it's fine, but if an SDK is using exceptions instead (like Python does), then it's not particularly easy to follow the control flow - the function throws an exception, and the value never gets assigned.I think I prefer @vito's suggestion of rich error types - I really really like the idea of being able to take any module object and wrap it into an error type (not just
messagestrings), which feels quite fun - you could have a rich linting report, with all your structured data, that's now an error. From a codegen POV, this could look a lot like how we haveExecErrtoday (this would be so cool to visualize in cloud as well).Although, potential weirdness - we'd essentially have a dynamic/generic error type in the core api. Is that an issue? How would that work? We definitely would need to do some fun extensions to get this.
jedevc commentedon Jan 13, 2025
Ok, so wanting to circle back to this, I actually have a concrete use case in #9356 I'd like to solve. Essentially, making a release now returns a "release report" - some of these operations might have failed.
The whole thing has actually failed - so I would want the
dagger callcommand to exit - but I still need to get the markdown report out as well. Ideally, runningdagger call -m releaser publish ... markdownwould return the report string onstdout, and alsoexit 1.I'd also like to be able to take this even further - suppose the report had an interactive container to play around with the results (e.g. to help debug test failures), then I should be able to do:
dagger call -m releaser publish ... container with-mounted-file ... terminalto mount a local tool into the debuggable container! I should be able to manipulate the returned value, even if the command will eventually exit with 1. This could also work with the prior discussed example of a directory of screenshots produced from a failed selium test.If we just had to consider go, then just
return &report, errwould be nice, as the original proposal suggests. We could even represent this neatly in the newdagger.Errortype. The problem comes when you would put this in Python or Typescript, where such a failure propagates to an exception, as I point out in #8421 (comment).If we do what I suggest there, and encode all the information into the error type, then we very quickly run into a problem:
What type does this function return? It can actually return a directory or a container! And we can't know which one until runtime (and we either error, or we don't). So doing something like
dagger call func with-exec ...may succeed or may fail to find thewith-execstep - depending on the error.So I think we get this important rule - if we attach a value to an error type, then it should be the same type as the function should normally return. And we should have a way to check that this is true.
One option for those languages could be to try the pattern here: https://github.com/castedo/unexceptional - essentially, allow returning errors directly instead of throwing them. If we did this, we could allow for module functions to use a go-like pattern for cases where you should be able to return a value and an error. All function calls to outside functions would still throw exceptions.
So, you could do:
Or even:
This allows us to return both values and errors - so we could do the original proposal that @marcosnils suggested.
Curious to hear what @helderco and @TomChv think of this pattern - since it seems like the easiest way to enforce the above bolded rule.
TomChv commentedon Jan 13, 2025
Yeah that's a great idea! It doable in Typescript too! Here's multiple solutions
1. Go style error
Then to check, we can just do internally
However, this will impact the user DX too, if he call some of its own function internally, he might have some pain dealing with that type of error handling since it's not native to the language.
2. Shadow error type
Maybe a utility function that wrap a result and return an error is preferable in term of DX, and this will just skip the type safety, the DX will be the same for the user, no additional typing, just a utility function to call
Example:
3. Custom Dagger Error with native style
We could even just let the user throw and add a custom error type that we can catch on our side to share both error & value, that could be even better IMO and doesn't disturb the DX.
Then internally we catch and check if that's a daggerError, then we look for the value.
I think solution 3 is the best for Typescript but let me know what you guys think
vito commentedon Jan 15, 2025
@TomChv I like the last option the most - assuming that's the closest to how errors would normally be used in TypeScript.
Same for Python I figure; each SDK runtime should catch errors/exceptions in the native manner and turn them into rich
dagger.Errorfunction return values.@jedevc Hrm, I don't think we need to worry about conflicting return types - to me, it's not "return type V on success and type E on error", it's "return type V, or return a GraphQL error" - GraphQL errors can come with their own type and fields, so it seems like a potential medium for sending rich errors back.
Errors are tricky: if you try to pre-declare "my function only returns V or an error of type E" - what happens when some unexpected error occurs, i.e. in a module dependency? I think we can't treat this like an
Optiontype; errors are their own thing, and asserting on their type dynamically at runtime is the "thing to do" in basically every language that deals with them. (I do like the type hint of "I intend to return these error types" - but don't really know how to apply it.)In an ideal world,
Errorwould actually be an interface:Then, today's
Errorwould instead becomeStandardErroror something, and if you wanted to return a*Containeralong with your error you would define your ownErrortype that just has it as a field.Then, when we're returning an
Errorfrom a function, we can send along the concrete type and pre-fetched fields using GraphQL error extensions. The client-side can then turn that into concrete error types known to the module so you can do type switches as normal, or it could return a generic error that preserves the type/fields if the type isn't directly exposed to it.ExecErrorwould become an actual error type in the API, instead of something special-cased in each SDK.I'm glossing over the hard bits here for sure, but I think that's what would feel most natural across SDKs.
Getting back to your original use case ("I want to attach to an errored container with
terminal") we might need some sort of syntax for "capture an error and continue the chain from it".So if you ran this, and it failed, we could print the error out nicely:
Or, more ideally, we would pop you into a
dagger shellwith the error already loaded as the current context:Something like that!
jedevc commentedon Jan 16, 2025
I kinda don't hate the
^😆But, I do think that having some "type" of what the returned value is is important. It's not important for the error to have any specific type, agreed that that could be an interface. But if you can just naturally continue the chain (e.g. getting the report and the error), it would be good to be able to statically type the continued value.
e.g. imagine constructing an ID for something like
dagger call foo ^ container. Until you run it, you can't determine ifcontaineris a property on the error, or what fields it even has, etc. I guess that's not a limitation for now? But it feels like it reduces the predictability of a command - now as the caller, I need to know how the module author has exactly produced their module to handle error cases (since different branches could return entirely different types to continue on).😆 regardless, I actually do agree with all your points that we should be able to implement our own
Errortypes - even if we don't support this "strongly-typed" pattern with multiple-returns, etc. Potentially it's possible to even do both 🤔 (e.g. if a a returnedErrorsupports aContinue() TwhereTis the return type of the function we can allow continuing from that point`).MatthiasGrandl commentedon Apr 3, 2025
Any news on this? This is kinda blocking me from adopting dagger for our CI.
vito commentedon May 5, 2025
@MatthiasGrandl Hi! Would you mind providing a few details on your use case?
There's been some progress depending on what you're after. Namely, our
ErrorAPI type supports having arbitrary named (JSON) values attached to it, which will get propagated back to the client. But it's currently an implementation detail - there are parts missing to make it ergonomic (like being able to return it as aGoerror or raise it as a Python exception, etc.).MatthiasGrandl commentedon May 6, 2025
@vito thanks for the reply! For example I have a job for running integration tests, which on fail returns junit test results that I need to export to get a nice report. Currently I have to workaround it with expect: any to then export the test results and then fail the pipeline afterwards.
nathan-joslin commentedon May 15, 2025
This is also affecting our team. Our workaround for tests/linters is to return an error if issues are found, and if users want to view the results they can re-run with an option to return an artifact (
string,*dagger.File, or*dagger.Directory).We considered adding the results to the error itself, but it limits the returned artifacts to a single string. This not only makes it a little troublesome for some linters that output to files, but if we want a module to run many linters in parallel the output becomes large and difficult to parse through.
vito commentedon May 23, 2025
@shykes Maybe there's an opportunity to allow typed values to be bound to an
Errorjust like they can be bound to anEnv? 🤔(context: #10370)
mgrinshpon commentedon Dec 26, 2025
This significantly hampers adoption of dagger for teams using gitlab - especially since they're the other major game in town after github's most recent rugpull.
Specifically, in gitlab, regardless of errors or types, gitlab wants reports to push various specially formatted files to given artifact directories.
dagger.cloud, however, has these lovely red spans that say "yo, this is broken!" A dagger job can emit a result to an external link and then users can click through into the dagger cloud link.
It would be awesome if teams using gitlab could have their cake and eat it, too - see the spans in dagger cloud as being broken AND see reports popping up in PRs.
It's not even like it'd be bad for github users! For example:
Tip for Gitlab users
If you are prioritizing gitlab reports over dagger.cloud traces, one workaround is something like this:
Then, in a script, you can do something like this to call out to the dagger engine:
I will say that making a shell script to call out to dagger to get what I kind of want to get in the first place feels like a violation of what dagger wants to do, but it does work and it's less painful than the medieval torture chamber that is gitlab ci.
If anyone figures out how to let that script have args, let me know, because I have not figured it out.
Unrequested $0.02
I do think that an ADT and/or Monad Result like in rust would be amazing here. It worked great for cloudflare!
But seriously, being able to do something like this feels like it'd a huge step in making dagger feel really nice:
Then, calls can still exit with an error code yet still emit results without going through the complexities of making bespoke .dagger scripts for each project in a repo: