Extend add_error to also support complex error arrays, hashes
We are using mutations in the Kontena Server, and we have two usecases related to validation errors that the current Mutations::Command API does not really support:
-
Reporting manual validation errors for multi-valued
arrayfields, such as when doing a DB lookup for each array item in thevalidatemethodOur current approach for validating such fields looks something like this:
GridServices::Common#validate_secrets_existoptional do array :secrets do hash do required do string :secret string :name end end enddef validate_secrets_exist(grid, secrets) secrets.each do |s| unless grid.grid_secrets.find_by(name: s[:secret]) add_error(:secrets, :not_found, "Secret #{s[:secret]} does not exist") end end endHowever, if there are multiple non-existant secrets in the
secretsarray, then we can only report one of those validation errors.Being able to report all of the resulting validation errors for each of the array items requires something to add a
Mutations::ErrorArrayto@errors, which is not supported by the current API. -
Nested mutations, where the
Stacks::Createmutation takes an array ofservicehashes, and passes each of those to theService::CreatemutationOur current approach of handling such nested outcome errors involves calling
add_errorfor each field in the resulting outcome errors hash:Stacks::Common#handle_service_outcome_errorsdef handle_service_outcome_errors(service_name, errors) errors.each do |key, atom| add_error("services.#{service_name}.#{key}", atom.symbolic, atom.message) end end def validate self.services.each do |service| outcome = GridServices::Create.validate(service) unless outcome.success? handle_service_outcome_errors(service[:name], outcome.errors) end end endHowever, while this works okay for simple sub-mutation errors, this fails badly on any validation errors for any
arrayfields, because there is no way to add the resultingMutations::ErrorArrayerror to the top-level mutation@errors. Currently this fails with aArgumentError (Invalid kind)when passing the array of symbols returned byMutations::ErrorArray#symbolictoadd_error: https://github.com/kontena/kontena/issues/2238#issuecomment-298569759The
merge_errorsmethod doesn't work either, because each of the identically-shaped sub-mutation outcome errors needs to be added as nested errors with some uniqueservices.fookey.
This PR extends the Mutations::Command#add_error to provide a solution for both of these uses-cases by also accepting structured Mutations::ErrorAtom, Mutations::ErrorArray and Mutations::ErrorHash errors with a structured key. The simple case of a add_error(key, :kind, "message") is implicitly converted to a Mutations::ErrorAtom.