gpt4 book ai didi

javascript - 如何只传递错误信息?

转载 作者:行者123 更新时间:2023-12-02 17:17:43 26 4
gpt4 key购买 nike

在服务中,我抛出带有不同消息的 HttpConflExceptions,如下所示:

public function shareLightbox(User $sharedToUser, User $sharedFromUser, LightBox $lightbox)
{
if ($lightbox->getCount() === 0) {
throw new ConflictHttpException("The folder contains no assets. Please add assets before sharing.");
}

if ($sharedToUser->hasRegistrationPending()) {
throw new ConflictHttpException("User has a pending registration issued. Please authorize user first.");
}

if ($sharedFromUser === $sharedToUser) {
throw new ConflictHttpException('You cannot share a folder with yourself.');
}

$wasLightboxAlreadyShared = $sharedToUser->hasAlreadySharedLightbox($lightbox);

if ($wasLightboxAlreadyShared) {
throw new ConflictHttpException('The user you want to share the folder with already owns it.');

...
}

在我的前端,我只想以纯文本方式获取抛出的错误消息。 xhr.responseText 渲染整个 html 页面。

$.ajax({
type: "POST",
url: shareLightboxUrl,
data: $shareForm.serialize(),
success: function() {
bootbox.hideAll();
bootbox.alert('The folder was successfully shared.');
},
statusCode: {
400: function(xhr, data, fnord) {
/**
* Wrong form data, reload form with errors
*/
$shareForm.html(xhr.responseText);
},
409: function(xhr, data, error) {
console.log('look here', xhr, data, error);
/**
* Unable to share lightbox
*/
bootbox.hideAll();
bootbox.alert(xhr.responseText); // THIS IS WHERE I WANT ONLY THE ERROR MESSAGE INSTEAD OF A FULLY RENDERED HTML ERROR PAGE
}
}
});

如何在 symfony2 中以可以直接访问异常消息的方式格式化异常?

最佳答案

您可以捕获异常并从那里处理它:

// use Symfony\Component\HttpFoundation\JsonResponse;
try
{
if ($lightbox->getCount() === 0) {
throw new ConflictHttpException("The folder contains no assets. Please add assets before sharing.");
}
}
catch( ConflictHttpException $e )
{
// use a handy json response with your http status
return new JsonResponse( $e->getMessage() , 409 );
}

关于javascript - 如何只传递错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24264194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com