如何只传递错误信息?

时间:2014-06-17 12:45:12

标签: 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 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中以这种方式格式化异常,我可以直接访问异常消息?

2 个答案:

答案 0 :(得分:2)

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

// 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 );
} 

答案 1 :(得分:0)

基本思路不是让Symfony2进入渲染阶段。相反,您需要拦截异常(kernel.exception事件)并执行:

return new Response("Error message", 400); // 400 is just an example