Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active May 19, 2018 18:13
Show Gist options
  • Save m8rge/47af92d4d827b1822b22 to your computer and use it in GitHub Desktop.
Save m8rge/47af92d4d827b1822b22 to your computer and use it in GitHub Desktop.
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