carono/yii2-validation-exception

An exception for the model in case of erroneous validation

dev-master 2025-07-31 16:40 UTC

This package is auto-updated.

Last update: 2025-07-31 16:43:22 UTC


README

License PHP Version

A simple Yii2 extension that provides a specialized exception class for handling model validation errors.

Features

  • Throws an exception with the first validation error message when model validation fails
  • Provides direct access to the failed model instance
  • Easy integration with Yii2 applications

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require carono/yii2-validation-exception

or add

"carono/yii2-validation-exception": "*"

to the require section of your composer.json file.

Usage

use carono\yii2\exceptions\ValidationException;
use yii\base\Model;

$model = new Model();
$model->addError('attribute', 'Validation error message');

// Throw exception with the first validation error
throw new ValidationException($model);

// Or use it in a try-catch block
try {
    if (!$model->validate()) {
        throw new ValidationException($model);
    }
    // Continue with valid model
} catch (ValidationException $e) {
    // Access the error message
    echo $e->getMessage(); // "Validation error message"
    
    // Access the model instance
    $failedModel = $e->model;
}

License

The MIT License (MIT). Please see License File for more information.

Author

Alexander Kasyanov - carono.ru - info@carono.ru