yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.23k stars 6.91k forks source link

REST API model custom error identification #11805

Open aliechti opened 8 years ago

aliechti commented 8 years ago

Sometimes it is important to know exactly which error has occurred with a REST API. This can be accomplished with an custom error code. I've done some research how Yii2 handles errors and it is not that easy to handle this at the moment.

Is this even possible?

What steps will reproduce the problem?

Force an error on the email validator.

What is the expected result?

[
  {
    "field": "email",
    "message": "email is not a valid email address.",
    "code": "some custom error code for identification"
  }
]

What do you get instead?

[
  {
    "field": "email",
    "message": "email is not a valid email address."
  }
]

Additional info

Q A
Yii version 2.0.8
cebe commented 8 years ago

This is currently not possible with Model itself, but you could set the error message as an array:

$model->addError('email', ['code' => 42, 'msg' => 'Email is invalid.']);

and adjust the Serializer::serializeModelErrors() method to format it like you need.

aliechti commented 8 years ago

@cebe Thanks for the workaround. But this is also not possible, because of the yii\validators\Validator->addError method, which uses Yii::$app->getI18n()->format on the message. This generates an error:

preg_match() expects parameter 2 to be string, array given
yiisoft\yii2\validators\Validator.php(379): yii\i18n\I18N->format()
cebe commented 8 years ago

you have to use addError() method of the model instead.