ValidatorException.php 1.13 KB
Newer Older
1 2
<?php

3
namespace Meibuyu\Micro\Exceptions;
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

use Hyperf\Utils\Contracts\MessageBag;

class ValidatorException extends \Exception
{
    /**
     * @var MessageBag
     */
    protected $messageBag;

    /**
     * @param MessageBag $messageBag
     */
    public function __construct(MessageBag $messageBag)
    {
        parent::__construct('The given data was invalid.');
        $this->messageBag = $messageBag;
    }

    /**
     * @return MessageBag
     */
    public function errors()
    {
        return $this->messageBag;
    }

    /**
     * @return string
     */
    public function first()
    {
        return $this->messageBag->first();
    }

    /**
     * Get the instance as an array.
     *
     * @return array
     */
    public function toArray(): array
    {
        return [
            'error' => 'validation_exception',
            'error_description' => $this->errors()
        ];
    }

    /**
     * Convert the object to its JSON representation.
     *
     * @param int $options
     * @return string
     */
    public function toJson($options = 0)
    {
        return json_encode($this->toArray(), $options);
    }

}