<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace App\Exception\Handler;
use Hyperf\Codec\Json;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;
class ValidationExceptionHandler extends ExceptionHandler
{
public function handle(Throwable $throwable, ResponsePlusInterface $response)
{
$this->stopPropagation();
/** @var ValidationException $throwable */
$body = $throwable->validator->errors()->first();
if (! $response->hasHeader('content-type')) {
$response = $response->addHeader('content-type', 'application/json; charset=utf-8');
}
$format = [
'success' => false,
'code' => 4001,
'message' => $body,
'data' => []
];
return $response->setStatus(200)->setBody(new SwooleStream(Json::encode($format)));
}
public function isValid(Throwable $throwable): bool
{
return $throwable instanceof ValidationException;
}
}
标签:body,ValidationExceptionHandler,content,hyperf,ValidationException,throwable,typ
From: https://www.cnblogs.com/xuyaoxiang1991/p/18378467