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
### Items
- [ ] Running as a script (don't capture catch-all exception → traceback and correct exit code)
- [ ] Use logging to handle exceptions without aborting
- [ ] Capture single query to prevent full pipeline failure (e.g., `exit_code()`)
Capturing catch-all exception
For simple scripts it's useful to let exceptions not be handled. They provide a traceback (stack trace) that can be useful in debugging the failure, especially since you'll be able to see the underlying exception catched by dagger, which can contain more information. The exception also exits with non-zero code so it's not necessary to do this:
However, if using logging to report issues (e.g., Sentry), running from an environment that you can't abort (e.g., webhook), or just needing to have greater control of how errors are reported (e.g., typer, rich), the catch-all dagger.DaggerError includes all dagger exceptions:
The API can return valid errors for a query (e.g., no such file or directory, failed to exec command...). If it's left unhandled it will abort the whole pipeline. To avoid that, just capture the dagger.QueryError exception. You can abort only the rest of a sub-pipeline by putting it in a function and returning, or control the flow in some other way. Example:
Hi @helderco, I'm currently working on implementing dagger's python SDK into one of my personal projects to handling linting and a bunch of other things (🤞).
Currently I'm trying to make the pipeline a bit more async (using the anyio task groups used in the enhancements area of the getting started guide), but I'm running into an issue with python errors and the dagger client.
tl;dr: Can you still somehow access stdout, stderr, & exit_code if the container returned a non-zero exit code
backstory:
I'm currently trying to use dagger to handle linting for all my python files, currently pylint isn't very happy with a lot of my files. As a linter though, this is fine to take note of it and bubble that error up eventually. I'm trying to collect all the potential issues with linters in a results list (which has a custom pydantic dataclass) to expose the relevant information later on.
The issue is I can't seem to access any of the information from the ran process (i.e. status code, stdout, stderr) from the dagger container without dagger throwing an exception which crashes the whole program on that line. I tried to catch the exception initially, and hope I could access the info afterwards w/o the exception but that doesn't appear to work.
So, it looks like the only thing I'm going to be able to do to access the return code, stdout, & stderr is regex all the info out of the error object... (what I'm seeing from the error object currently):
Is it possible that I'm over complicating this, or am I looking at it the wrong way and the info is currently available for a failed execution of the dagger container?
If you wanted to replicate what I'm currently doing you can do the following:
Then you should have the exact environment I'm running things in, and be able to get the same error. With the -p flag, I'm only running the python linting but the idea is if you add a bunch of other flags it'll do ansibe, terraform, etc. linting. I'm just doing python now to keep things simple.
Currently I'm printing out a bunch about the error to see if there was anything else I could access, but I'm not using any of that.
Those fields trigger the configured exec to run. Problem is that if the command fails, the common code that they all share returns an error. That isn’t the proper behavior. A proper GraphQL error would be for example that no exec was actually configured, or the network connection was suddenly killed.
This happened initially because we had a technical limitation, but we have a way to walk around it now. However, there’s reluctance in fixing them because it means breaking a lot of users that have now come to depend on this current behavior.
That’s why I’m in the process of writing a few proposals to make this better. I basically want to create a new field in the API that returns a result object with these fields, without raising an exception.
In the meantime though, you need to extract the relevant data from the error message if the command fails. Here's an example of what you can do (pseudo):
@dataclassclassExecResult:
stdout: strstderr: strexit_code: interror: str|None=Noneasyncdefexec(ctr: dagger.Container) ->ExecResult:
try:
returnExecResult(
awaitctr.stdout(),
awaitctr.stderr(),
awaitctr.exit_code(),
)
exceptdagger.QueryErrorase:
msg=str(e)
if"exit code:"notinmsg:
# this could be a network error for exampleraise# basically extract the various components from the error message# this is the format:# <returned error message with included "exit code: %d"># Stdout:# <stdout># Stderr:# <stderr>returnExecResult(
stdout_from_error(msg),
stderr_from_error(msg),
exit_code_from_error(msg),
error_message(msg),
)
asyncdeflint(client: dagger.Client):
ctr=client.container()...
result=awaitexec(ctr)
# you can choose what to do with the error# (e.g., abort, log, ignore...)ifresult.error:
raiseMyCustomError(result.error)
In the future, if we add this to the API, then you’d just delete your function and use the new field instead:
- result = await exec(ctr)+ result = await ctr.exec()
Lol, I know Gerhard (who I heard that phrase from) is on the team, but I didn't know if it would come off the wrong way if you didn't know the context so I tried to say it in a more polite way 😅.
I actually learned about this project from @gerhard listening to ShipIt 🥳 (BTW still looking forward to the continued ShipIt updates, even if they are less frequent 🙂 ).
I'd been interested in learning CUE (when I'd learned about it on GoTime), but just didn't/don't have time for it. So when I'd heard Gerhard mention about dagger using CUE underneath I though I'd check out dagger when I had the time, but still didn't have time. So, when I heard about the SDK support for other languages I was super excited, because it made it so much more approachable 🥳. I've implemented (even though it's in alpha 😅) into some work CI/CD pipelines that were very ...finicky... and it's made life so much easier 🥳
Thanks for maintaining this amazing project! 🥳
Actual response
We have an outstanding bug...without raising an exception.
That sounds awesome! Thank you so much for the amazing hard work! 🥳
In the meantime though...
That's actually pretty similar to my initial attempt 😅
I didn't think to capture the error message though, I'll grab that so I can check it and raise it if it's something I'm not expecting 😁 I also like the dataclass return instead of using an object, so I might reuse your implementation 🙂
Anyone that runs into this issue feel free to re-use regex my regex:
One thing that's different from your solution vs mine is I'm appending + "CUSTOM_EOF" to give something a bit more concrete for my regex to know it's the end vs just a .*.
Something else identified (mainly for others using this hack)
Something I did notice is that it seems like the internal stdout representation (which lead me to believe it'll happen for stderr) seems to have some type of limit to how long of a string it'll present to the user when accessing the QueryError object.
For example, when doing the equivalent of a print(query_err_msg), this is the beginning of the Stdout section:
Stdout:
o snake_case naming style (invalid-name)
When typically pylint's output starts with something like this:
************* Module models.config
ci/dagger/models/config.py:6:0: C0115: Missing class docstring (missing-class-docstring)
letting you know which file it's checking before outputting the error.
So, you can't grab all of the output when parsing for it. For me that's not super bad, I'll just need to incrementally work on fixing the linting errors and eventually it'll be small enough to show everything 😅. For other's that'll need access to the entire error message it'll potentially prevent them if there's a lot of text in the output.
It's also visible if you print something like query_err.__dict__ to print out it's internal representation of the object. (below is mine)
{'errors': [QueryErrorValue(message='process "pipenv run pylint --rcfile .linting-configs/pylintrc ci/dagger/automation.py ci/dagger/async_interface.py ci/dagger/models/linting.py ci/dagger/models/config.py ci/dagger/linting.py ci/dagger/helper.py" did not complete successfully: exit code: 28\nStdout:\no snake_case naming style (invalid-name)\n************* Module models.linting\nci/dagger/models/linting.py:9:0: C0115: Missing class docstring (missing-class-docstring)\nci/dagger/models/linting.py:15:22: C0103: Argument name "v" doesn\'t conform to snake_case naming style (invalid-name)\nci/dagger/models/linting.py:33:0: C0115: Missing class docstring (missing-class-docstring)\nci/dagger/models/linting.py:44:4: C0115: Missing class docstring (missing-class-docstring)\nci/dagger/models/linting.py:44:4: R0903: Too few public methods (0/2) (too-few-public-methods)\nci/dagger/models/linting.py:33:0: R0903: Too few public methods (1/2) (too-few-public-methods)\nci/dagger/models/linting.py:48:0: C0115: Missing class docstring (missing-class-docstring)\n************* Module models.config\nci/dagger/models/config.py:6:0: C0115: Missing class docstring (missing-class-docstring)\nci/dagger/models/config.py:6:0: R0903: Too few public methods (0/2) (too-few-public-methods)\n************* Module linting\nci/dagger/linting.py:37:4: W0613: Unused argument \'client\' (unused-argument)\nci/dagger/linting.py:179:4: W0613: Unused argument \'client\' (unused-argument)\nci/dagger/linting.py:240:4: W0613: Unused argument \'client\' (unused-argument)\nci/dagger/linting.py:301:4: W0613: Unused argument \'client\' (unused-argument)\nci/dagger/linting.py:5:0: W0611: Unused import click (unused-import)\nci/dagger/linting.py:7:0: W0611: Unused QueryError imported from dagger.exceptions (unused-import)\n************* Module helper\nci/dagger/helper.py:51:0: C0116: Missing function or method docstring (missing-function-docstring)\nci/dagger/helper.py:88:0: C0115: Missing class docstring (missing-class-docstring)\nci/dagger/helper.py:122:0: C0116: Missing function or method docstring (missing-function-docstring)\nci/dagger/helper.py:133:19: W0212: Access to a protected member _raw_input of a client class (protected-access)\nci/dagger/helper.py:1:0: W0611: Unused getenv imported from os (unused-import)\n\n-----------------------------------\nYour code has been rated at 8.45/10\nStderr:\n', locations=[QueryErrorLocation(line=24, column=25)], path=['container', 'from', 'withMountedDirectory', 'withWorkdir', 'withMountedCache', 'withMountedCache', 'withExec', 'withEnvVariable', 'withEnvVariable', 'withExec', 'withExec', 'stdout'])], 'query': DocumentNode}
Side comment
Don't know where the best place to post this, but it might be useful to (eventually) bring back something like how the universe.dagger.io used to be (had to go a few releases back to show what it actually looked like: https://github.com/dagger/dagger/tree/v0.2.36/pkg/universe.dagger.io). So people could create re-usable code snippets (i.e. accepts a dagger.Client or dagger.Container to setting up caches for python & installing deps, and returns a dagger.Container to continue to add to). I figure this is probably something that'll be wanted (probably after a v1 release 🙃 ) and you/the team don't have time to get to it yet, but just figured I'd mention it in case it wasn't thought of yet 🙂
I don't know how you're doing the generation of python code (noticed there's a dagger.api.gen import), but something that's potentially analogous is how aws-cdk has something like the aws-cdk-libs package. IIRC they use typescript on the backend and then transpile to their supported languages.
(pitch for why) Having a plugin library like that would help people get up to speed quicker, so they don't have to re-implement everything for every project.
Lol, I know Gerhard (who I heard that phrase from) is on the team, but I didn't know if it would come off the wrong way if you didn't know the context so I tried to say it in a more polite way 😅.
No prob 🙂 That quote comes from a Steve Jobs response, after users reporting issues will cell phone reception with the iPhone 4. It has become a meme. 😄
[...] and it's made life so much easier 🥳
I'm glad you're finding Dagger useful! 🥳
I didn't think to capture the error message though [...]
Yes, it's mainly useful to see the actual command that was run. It's also where the exit code is. Here’s the general format:
One thing that's different from your solution vs mine is I'm appending + "CUSTOM_EOF" to give something a bit more concrete for my regex to know it's the end vs just a .*.
Thanks! 👍
Something else identified (mainly for others using this hack)
Something I did notice is that it seems like the internal stdout representation (which lead me to believe it'll happen for stderr) seems to have some type of limit to how long of a string it'll present to the user when accessing the QueryError object.
I’m not aware of that, I’ll need a simple example to reproduce. If you’re able to do it and create an issue for it, that would be helpful. 🙏
Side comment
Don't know where the best place to post this, but it might be useful to (eventually) bring back something like how the universe.dagger.io used to be (had to go a few releases back to show what it actually looked like: https://github.com/dagger/dagger/tree/v0.2.36/pkg/universe.dagger.io). So people could create re-usable code snippets (i.e. accepts a dagger.Client or dagger.Container to setting up caches for python & installing deps, and returns a dagger.Container to continue to add to). I figure this is probably something that'll be wanted (probably after a v1 release 🙃 ) and you/the team don't have time to get to it yet, but just figured I'd mention it in case it wasn't thought of yet 🙂
Yes, for things that are very common and if it makes sense, we prefer adding to the core API. That way it can automatically be generated for all supported SDKs. That’s what I meant above when I said that “I’m in the process of writing a few proposals to make this better.” By “this”, I mean in this specific case, where if implemented, the example usage would stay the same, you’d just need to change this:
- result = await exec(ctr)+ result = await ctr.exec()
I’ll reference the proposals here when they’re published.
When that’s not possible, I’ve also considered adding SDK helpers (another forthcoming issue that I want to write) to abstract a few common patterns that I see users having the need to implement themselves. That takes more work and needs a different implementation in each SDK.
In this particular case, I want to avoid it because of the proposal to make an API change. That would require users to change their usage pattern twice.
Expanding scope a bit more, we do have plans to support what we call “extensions”:
The purpose of those is to extend the API with your own code. That can be implemented in one SDK, but consumed in another SDK, so there’s no fragmentation. It’s a way to define and share core that’s re-usable across any Dagger SDK.
In the meantime however, you can still put any Python code in a reusable library that can be installed with pip, privately or not, within your own projects or with others.
asyncdeflint(client: dagger.Client):
try:
awaitclient.container().from_("alpine").with_exec(["false"])
exceptdagger.ExecErrorase:
# you can choose what to do with the error# (e.g., abort, log, ignore...)# e.message# e.exit_code# e.stdout# e.stderr# e.cmdraiseMyCustomError(e.stderr)
Activity
[-]Python error handling guide[/-][+]📖 Python error handling guide[/+]elreydetoda commentedon Apr 5, 2023
Hi @helderco, I'm currently working on implementing dagger's python SDK into one of my personal projects to handling linting and a bunch of other things (🤞).
Currently I'm trying to make the pipeline a bit more async (using the anyio task groups used in the enhancements area of the getting started guide), but I'm running into an issue with python errors and the dagger client.
tl;dr: Can you still somehow access stdout, stderr, & exit_code if the container returned a non-zero exit code
backstory:
I'm currently trying to use dagger to handle linting for all my python files, currently pylint isn't very happy with a lot of my files. As a linter though, this is fine to take note of it and bubble that error up eventually. I'm trying to collect all the potential issues with linters in a results list (which has a custom pydantic dataclass) to expose the relevant information later on.
The issue is I can't seem to access any of the information from the ran process (i.e. status code, stdout, stderr) from the dagger container without dagger throwing an exception which crashes the whole program on that line. I tried to catch the exception initially, and hope I could access the info afterwards w/o the exception but that doesn't appear to work.
So, it looks like the only thing I'm going to be able to do to access the return code, stdout, & stderr is regex all the info out of the error object... (what I'm seeing from the error object currently):
Is it possible that I'm over complicating this, or am I looking at it the wrong way and the info is currently available for a failed execution of the dagger container?
If you wanted to replicate what I'm currently doing you can do the following:
Then you should have the exact environment I'm running things in, and be able to get the same error. With the
-pflag, I'm only running the python linting but the idea is if you add a bunch of other flags it'll do ansibe, terraform, etc. linting. I'm just doing python now to keep things simple.Currently I'm printing out a bunch about the error to see if there was anything else I could access, but I'm not using any of that.
helderco commentedon Apr 6, 2023
Hey @elreydetoda, you’re not “holding it wrong”! 😅
We have an outstanding bug when using
exit_code,stdoutandstderr:Container { exitCode }doesn't work if the command fails #3192Those fields trigger the configured exec to run. Problem is that if the command fails, the common code that they all share returns an error. That isn’t the proper behavior. A proper GraphQL error would be for example that no exec was actually configured, or the network connection was suddenly killed.
This happened initially because we had a technical limitation, but we have a way to walk around it now. However, there’s reluctance in fixing them because it means breaking a lot of users that have now come to depend on this current behavior.
That’s why I’m in the process of writing a few proposals to make this better. I basically want to create a new field in the API that returns a result object with these fields, without raising an exception.
In the meantime though, you need to extract the relevant data from the error message if the command fails. Here's an example of what you can do (pseudo):
In the future, if we add this to the API, then you’d just delete your function and use the new field instead:
elreydetoda commentedon Apr 8, 2023
"holding it wrong"
Lol, I know Gerhard (who I heard that phrase from) is on the team, but I didn't know if it would come off the wrong way if you didn't know the context so I tried to say it in a more polite way 😅.
I actually learned about this project from @gerhard listening to ShipIt 🥳 (BTW still looking forward to the continued ShipIt updates, even if they are less frequent 🙂 ).
I'd been interested in learning CUE (when I'd learned about it on GoTime), but just didn't/don't have time for it. So when I'd heard Gerhard mention about dagger using CUE underneath I though I'd check out dagger when I had the time, but still didn't have time. So, when I heard about the SDK support for other languages I was super excited, because it made it so much more approachable 🥳. I've implemented (even though it's in alpha 😅) into some work CI/CD pipelines that were very ...finicky... and it's made life so much easier 🥳
Thanks for maintaining this amazing project! 🥳
Actual response
That sounds awesome! Thank you so much for the amazing hard work! 🥳
That's actually pretty similar to my initial attempt 😅
https://github.com/elreydetoda/packer-kali_linux/blob/782d002476fce2658761ebf6ac896c4b3d6eadee/ci/dagger/helper.py#L89-L143
I didn't think to capture the error message though, I'll grab that so I can check it and raise it if it's something I'm not expecting 😁 I also like the dataclass return instead of using an object, so I might reuse your implementation 🙂
Anyone that runs into this issue feel free to re-use regex my regex:
Here's a regex101 link explaining what I'm doing (including the extra flags I'm passing for the regex compilation) : https://regex101.com/r/4gebOv/
One thing that's different from your solution vs mine is I'm appending
+ "CUSTOM_EOF"to give something a bit more concrete for my regex to know it's the end vs just a.*.Something else identified (mainly for others using this hack)
Something I did notice is that it seems like the internal stdout representation (which lead me to believe it'll happen for stderr) seems to have some type of limit to how long of a string it'll present to the user when accessing the QueryError object.
For example, when doing the equivalent of a
print(query_err_msg), this is the beginning of the Stdout section:When typically pylint's output starts with something like this:
letting you know which file it's checking before outputting the error.
So, you can't grab all of the output when parsing for it. For me that's not super bad, I'll just need to incrementally work on fixing the linting errors and eventually it'll be small enough to show everything 😅. For other's that'll need access to the entire error message it'll potentially prevent them if there's a lot of text in the output.
It's also visible if you print something like
query_err.__dict__to print out it's internal representation of the object. (below is mine)Side comment
Don't know where the best place to post this, but it might be useful to (eventually) bring back something like how the universe.dagger.io used to be (had to go a few releases back to show what it actually looked like: https://github.com/dagger/dagger/tree/v0.2.36/pkg/universe.dagger.io). So people could create re-usable code snippets (i.e. accepts a
dagger.Clientordagger.Containerto setting up caches for python & installing deps, and returns a dagger.Container to continue to add to). I figure this is probably something that'll be wanted (probably after a v1 release 🙃 ) and you/the team don't have time to get to it yet, but just figured I'd mention it in case it wasn't thought of yet 🙂I don't know how you're doing the generation of python code (noticed there's a
dagger.api.genimport), but something that's potentially analogous is how aws-cdk has something like theaws-cdk-libs package. IIRC they use typescript on the backend and then transpile to their supported languages.(pitch for why) Having a plugin library like that would help people get up to speed quicker, so they don't have to re-implement everything for every project.
helderco commentedon Apr 10, 2023
No prob 🙂 That quote comes from a Steve Jobs response, after users reporting issues will cell phone reception with the iPhone 4. It has become a meme. 😄
I'm glad you're finding Dagger useful! 🥳
Yes, it's mainly useful to see the actual command that was run. It's also where the exit code is. Here’s the general format:
dagger/core/gateway.go
Line 194 in 4be9d6e
With
returnErrbeing something like:Example of an unknown command:
Example of a failed command:
Thanks! 👍
I’m not aware of that, I’ll need a simple example to reproduce. If you’re able to do it and create an issue for it, that would be helpful. 🙏
Yes, for things that are very common and if it makes sense, we prefer adding to the core API. That way it can automatically be generated for all supported SDKs. That’s what I meant above when I said that “I’m in the process of writing a few proposals to make this better.” By “this”, I mean in this specific case, where if implemented, the example usage would stay the same, you’d just need to change this:
I’ll reference the proposals here when they’re published.
When that’s not possible, I’ve also considered adding SDK helpers (another forthcoming issue that I want to write) to abstract a few common patterns that I see users having the need to implement themselves. That takes more work and needs a different implementation in each SDK.
In this particular case, I want to avoid it because of the proposal to make an API change. That would require users to change their usage pattern twice.
Expanding scope a bit more, we do have plans to support what we call “extensions”:
The purpose of those is to extend the API with your own code. That can be implemented in one SDK, but consumed in another SDK, so there’s no fragmentation. It’s a way to define and share core that’s re-usable across any Dagger SDK.
In the meantime however, you can still put any Python code in a reusable library that can be installed with pip, privately or not, within your own projects or with others.
helderco commentedon Apr 11, 2023
@elreydetoda:
exitCode,stdoutandstderrwith new pattern #4921helderco commentedon Jun 1, 2023
@elreydetoda, we now have a custom
dagger.ExecError:elreydetoda commentedon Jun 6, 2023
Awesome! Thanks for heads up @helderco , I'll give it a try in my project when I can 😁🥳
helderco commentedon Jul 27, 2023
Closing in favor of a general guide, for all SDKs.
mircubed commentedon Aug 1, 2023
@helderco is there an issue that we should link to this one that mentions the general guide, so we can keep following the efforts there?
helderco commentedon Aug 1, 2023
You can follow here: