[英]Symfony2, FOSRestBundle - catch exceptions
我有Symfony應用程序,我使用FOSRestBundle與AngularJS。 我的Symfony應用程序沒有任何視圖。
我想在AngularJS消息中顯示有關從服務器接收的信息,使用ngToast模塊。
如果我創建或更新它,很容易顯示。 但是如果服務器拋出一些異常? 例如,Angular客戶端嘗試獲取具有錯誤ID的項目,或者此用戶沒有訪問權來執行此操作? 在這種情況下,服務器將拋出異常,但我想顯示適當的消息。
symfony可以捕獲此異常,例如將其轉換為Response對象嗎? 例如 - 如果我沒有訪問異常,symfony應該捕獲它並做出類似這樣的事情:
return new Response(400, "You don't have permission to acces this route");
和Angular會得到:
{
"code": 400,
"message": "You don't have permission to acces this route"
}
可能嗎? 我該怎么辦? 也許我應該以其他方式去做。
我建議采用更多的FOSRestBundle方法,即配置例外,是否應該顯示消息:
fos_rest:
exception:
enabled: true
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': HTTP_FORBIDDEN
messages:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': true
假設您對某個操作有自定義的AccessDeniedException,您可以創建異常然后將其放入配置中。
<?php
class YouCantSummonUndeadsException extends \LogicException
{
}
無論你扔到哪里:
<?php
throw new YouCantSummonUndeadsException('Denied!');
你可以配置它:
codes:
'My\Custom\YouCantSummonUndeadsException': HTTP_FORBIDDEN
messages:
'My\Custom\YouCantSummonUndeadsException': true
並獲得如下結果:
{
"code": 403,
"message": "Denied!"
}
我希望這更清楚!
是的當然這是可能的。 我建議你實現一個簡單的Exception監聽器。 並使所有異常類擴展BaseException或實現BaseException,因此您將知道哪些異常來自“您的”代碼。
class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
// Do your stuff to create the response, for example response status code can be exception code, and exception message can be in the body or serialized in json/xml.
$event->setResponse($response);
return;
}
}
在容器中注冊:
<service id="your_app.listener.exception" class="App\ExceptionListener">
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.