Javascript 如何只传递错误消息?
在一个服务中,我抛出一个HttpConflExceptions,其中包含不同的消息,如下所示:Javascript 如何只传递错误消息?,javascript,jquery,symfony,exception-handling,Javascript,Jquery,Symfony,Exception Handling,在一个服务中,我抛出一个HttpConflExceptions,其中包含不同的消息,如下所示: public function shareLightbox(User $sharedToUser, User $sharedFromUser, LightBox $lightbox) { if ($lightbox->getCount() === 0) { throw new ConflictHttpException("The folder contains no as
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.');
...
}
在前端,我只想以纯文本的方式获取抛出的错误消息。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中格式化异常,以便直接访问异常消息?基本思想是不要让symfony2进入渲染阶段。相反,您需要截获异常(
kernel.exception
event)并执行以下操作:
您可以捕获异常并从此处进行处理:
// 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 );
}
// 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 );
}