Skip to content

Instantly share code, notes, and snippets.

@m8rge m8rge/ CantSave.php
Last active May 19, 2018

Embed
What would you like to do?
Yii2 exception for non-saved active records
<?php
namespace common\exception;
use e96\sentry\ErrorHandler;
use yii\base\Exception;
use yii\db\ActiveRecord;
class CantSave extends Exception
{
/**
* @var mixed model errors
*/
protected $errors;
/**
* @var mixed model attributes
*/
protected $attributes;
/**
* @param ActiveRecord $model
* @param string $message
* @param int $code
* @param \Exception $previous
* @throws \yii\base\InvalidConfigException
*/
public function __construct($model, $message = "", $code = 0, \Exception $previous = null)
{
$this->errors = $model->errors;
$this->attributes = $model->attributes;
/** @var ErrorHandler $raven */
$raven = \Yii::$app->get('raven', false);
if ($raven) {
$raven->client->extra_context(
[
'errors' => $this->errors,
'attributes' => $this->attributes
]
);
\Exception::__construct('Can\'t save ' . get_class($model), $code, $previous);
} else {
\Exception::__construct(
'Can\'t save ' . get_class($model) . ': ' . print_r($this->errors, true) .
'Attributes: ' . print_r($this->attributes, true),
$code,
$previous
);
}
}
}
<?php
namespace common\models;
use common\exception\CantSave;
class ActiveRecord extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
* @throws CantSave
*/
public function save($runValidation = true, $attributeNames = null)
{
$res = parent::save($runValidation, $attributeNames);
if (!$res) {
throw new CantSave($this);
}
return $res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.