Skip to content

Commit

Permalink
NEW Show more information in ValidationException message
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Jan 30, 2025
1 parent 3a69e16 commit 263d324
Show file tree
Hide file tree
Showing 10 changed files with 460 additions and 217 deletions.
3 changes: 2 additions & 1 deletion src/Core/Validation/ConstraintValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ class ConstraintValidator
/**
* Validate a value by a constraint
*
* @param $value The value to validate
* @param Constraint|Constraint[] $constraints a constraint or array of constraints to validate against
* @param string $fieldName The field name the value relates to, if relevant
* @param $fieldName The field name the value relates to, if relevant
*/
public static function validate(mixed $value, Constraint|array $constraints, string $fieldName = ''): ValidationResult
{
Expand Down
31 changes: 31 additions & 0 deletions src/Core/Validation/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
use Exception;
use InvalidArgumentException;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Control\Director;
use SilverStripe\Dev\DevelopmentAdmin;
use SilverStripe\ORM\DataObject;
use SilverStripe\Control\Controller;

/**
* Exception thrown by {@link DataObject}::write if validation fails. By throwing an
Expand Down Expand Up @@ -48,6 +52,16 @@ public function __construct($result = null, $code = 0)
// Pick first message
foreach ($result->getMessages() as $message) {
$exceptionMessage = $message['message'];
if ($this->doShowAdditionalInfo()) {
if ($message['fieldName']) {
$exceptionMessage .= ' - fieldName: ' . $message['fieldName'];
}
$dataClass = $result->getDataClass();
if (is_subclass_of($dataClass, DataObject::class, true)) {
$exceptionMessage .= ', recordID: ' . $result->getRecordID();
$exceptionMessage .= ', dataClass: ' . $dataClass;
}
}
break;
}
} elseif (is_string($result)) {
Expand All @@ -71,4 +85,21 @@ public function getResult()
{
return $this->result;
}

/**
* Whether to show additional information in the error message depending on the context
*
* We do not want this to show this in a context where it's easy to know the record and value that
* triggered the error e.g. form submission, API calls, etc
*/
private function doShowAdditionalInfo()
{
if (Director::is_cli()) {
return true;
}
// e.g. dev/build
if (is_a(Controller::curr(), DevelopmentAdmin::class)) {
return true;
}
}
}
Loading

0 comments on commit 263d324

Please sign in to comment.