如何在Mix Task中返回指定退出码以适配CI构建流程?
Great question! The run/1 callback docs don't explicitly cover this, but there's a straightforward way to return custom exit codes that your CI system will pick up on.
The key tool here is System.halt/1 — this function immediately terminates the Erlang VM with the exit code you specify. Unlike throwing an exception (which defaults to exit code 1), System.halt/1 lets you use any integer to mark different failure types, perfect for distinguishing between configuration errors, missing dependencies, etc.
Here's a concrete example of how to implement this in your Mix Task:
defmodule Mix.Tasks.Ci.Validate do use Mix.Task @impl true def run(_args) do case perform_validation() do :success -> Mix.shell().info("✅ Validation passed!") :invalid_env -> Mix.shell().error("❌ Invalid environment variables set") System.halt(1) # Mark environment-related failure :broken_deps -> Mix.shell().error("❌ Dependency check failed") System.halt(2) # Mark dependency-related failure :data_mismatch -> Mix.shell().error("❌ Data integrity check failed") System.halt(3) # Mark data-related failure end end defp perform_validation do # Replace this with your actual CI validation logic :invalid_env end end
Important Notes:
System.halt/1is immediate — any code after this call won't execute. Make sure you've logged all necessary error messages or completed critical cleanup before calling it.- CI systems (like GitHub Actions, GitLab CI, or Jenkins) will automatically detect the exit code from the Mix process. A non-zero code will trigger a build failure, exactly what you need.
- If you don't call
System.halt/1, Mix will default to exit code 0 on success, or 1 if an uncaught exception is raised.
This approach is the standard way to handle custom exit codes in Elixir for CI workflows, and it plays nicely with all major CI platforms.
内容的提问来源于stack exchange,提问作者nietaki

