Commit 981bbae5 authored by 王源's avatar 王源 🎧

添加通用外键关联异常捕获

parent 6d9abb9a
...@@ -18,6 +18,7 @@ class ConfigProvider ...@@ -18,6 +18,7 @@ class ConfigProvider
'handler' => [ 'handler' => [
'http' => [ 'http' => [
\Meibuyu\Micro\Exceptions\Handler\MicroExceptionHandler::class, \Meibuyu\Micro\Exceptions\Handler\MicroExceptionHandler::class,
\Meibuyu\Micro\Exceptions\Handler\QueryExceptionHandler::class,
], ],
], ],
], ],
......
<?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;
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment