QueryExceptionHandler.php 1.23 KB
Newer Older
1 2 3 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
<?php

/**
 * Created by PhpStorm.
 * User: zero
 * Date: 2020/5/12
 * Time: 16:11
 */

namespace Meibuyu\Micro\Exceptions\Handler;


use Hyperf\Database\Exception\QueryException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class QueryExceptionHandler extends ExceptionHandler
{

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $code = $throwable->getCode();
        $msg = $throwable->getMessage();
        if ($code == 23000 && strpos($msg, 'foreign key') !== false) {
            // 格式化输出
            $data = json_encode([
                'code' => 400,
                'msg' => '此数据下有关联的数据,不可进行操作',
            ], JSON_UNESCAPED_UNICODE);
            // 阻止异常冒泡
            $this->stopPropagation();
            return $response
                ->withAddedHeader('content-type', 'application/json')
                ->withBody(new SwooleStream($data));
        }
        return $response; // 交给下一个异常处理器
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof QueryException;
    }
45 46

}