Use error codes in validation constraints

Created on 28 November 2024, 4 months ago

Problem/Motivation

The Symfony validator component supports error codes that can be used to programmatically handle specific error. Each validator can add multiple violations that may occur for different reasons for the given value. Using the violation message to detect what the exact error is, is not reliable:

- The message can change.
- The same message can be used for multiple errors.

Symfony constraints use UUIDs for error codes, making them unique. By incorporating the same system in Drupal constraints, contrib and custom modules can choose, for example, to ignore specific errors while responding to others. Modules exposing API endpoints, such as jsonapi, can also include the error codes in their responses offering the same capabilities to API clients.

Steps to reproduce

Call the $violation->getCode() on any violation and observe that it is always empty

Proposed resolution

- Add UUIDs as error code constants on all constraints.
- Each specific error case should have a distinct error code.
- Set the error code when building violations using the setCode() method, in all validators.

Remaining tasks

This is intended to be a meta-task. There are a lot of constraint/validator providers and to update all of them at once including updating/writing tests would be a lot of work. The best is to update each Drupal core module/component separately; one does not have to wait for the other to be included in a release.

Create tasks for the following:

Constraint providers

- Config component
- Entity component
- Extension component
- Path component
- Plugin component
- Validation component
- block_content module
- book module
- ckeditor5 module
- comment module
- content_moderation module
- content_translation module
- datetime module
- file module
- link module
- media module
- menu_link_content module
- menu_ui module
- path module
- taxonomy module
- user module
- workspaces module

Constraint users

- JSON:API - include error code in the responses.
- Anything else?

User interface changes

None.

Introduced terminology

Violation codes as used by the Symfony validator component are now introduced in the Drupal validator component.

API changes

This seems to not incur any backward-breaking changes. It only adds new capabilites.

Data model changes

None.

Release notes snippet

Constraint violations built by validators provided by Drupal Core now hold an error code that is different for each specific violation case. The error code can be retrieved by calling $violation->getCode()

Feature request
Status

Active

Version

11.0 🔥

Component

typed data system

Created by

🇵🇪Peru krystalcode

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024