Shopware 6管理:catch api错误



在我的自定义插件中,我向服务器发送write请求,服务器响应系统(500)错误:
POST http://0.0.0.0:8080/api/my-entity 500 (Internal Server Error)

错误是已知的和预期的,它来自数据库,因为重复的条目:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test' for key 'my_entity.name'

但是,我如何或在哪里捕捉和处理服务器端的错误,以清除错误消息?我已经找到了这个描述,但我会在响应之前处理错误,以设置正确的http错误。

错误处理似乎是一个错误

对于这个特定的用例,使用WriteCommandExceptionEvent而不是PreWriteValidationEvent:更合适

// MyEntityValidationSubscriber.php
<?php declare(strict_types=1);
...
use MyPluginDALExceptionDuplicateEntryException;
use ShopwareCoreFrameworkDataAbstractionLayerWriteCommandInsertCommand;
use ShopwareCoreFrameworkDataAbstractionLayerWriteValidationWriteCommandExceptionEvent;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
class MyEntityValidationSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
WriteCommandExceptionEvent::class => 'onWriteCommandException'
];
}
public function onWriteCommandException(WriteCommandExceptionEvent $event)
{
foreach($event->getCommands() as $command) {
if($command->getEntityName() !== 'my_entity') {
continue;
}
$haystack = $event->getException()->getMessage();
$needleDuplication = "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry";
$needleProperty = "key 'my_entity.name'";
if(
$command instanceof InsertCommand
&& strpos($haystack, $needleDuplication) !== false
&& strpos($haystack, $needleProperty) !== false
) {
throw new DuplicateEntryException('violation.unique.myEntityName');
}
}
}
}

Excpetion级

// DuplicateEntryException.php
<?php declare(strict_types=1)
...
use ShopwareCoreFrameworkShopwareHttpException;
use SymfonyComponentHttpFoundationResponse;
class DuplicateEntryException extends ShopwareHttpException
{
public function __construct(string $message, array $parameters = [], ?Throwable $e = null)
{
parent::__construct($message);
}
public function getErrorCode(): string
{
return 'DAL_DUPLICATE_ENTRY_EXCEPTION';
}
public function getStatusCode(): int
{
return Response::HTTP_BAD_REQUEST;
}
}

相关内容

  • 没有找到相关文章

最新更新