Yea*_*eak 3 php exception-handling symfony
我试图弄清楚如何制作自定义异常行为.当我抛出异常时使用
throw new \Exception('Error occurred with your request please try again');
Run Code Online (Sandbox Code Playgroud)
我自动获取状态500,并将消息作为内部服务器错误
但是,我希望我的响应包括我的异常消息,而不仅仅是内部服务器错误,所以它显示如下:
{
"error":{
"code":500,
"message":"Error occurred with your request please try again"
}
}
Run Code Online (Sandbox Code Playgroud)
最重要的是可能会做一些额外的事情,比如给自己发错误.但是我只想在我抛出一个\ Exception而不是使用类似的东西时发生这种情况
throw new HttpException
Run Code Online (Sandbox Code Playgroud)
关于如何实现这一目标的任何帮助或想法.
我还应该提一下,我没有使用Twig或任何模板.这完全是API类型响应
请查看http://symfony.com/doc/current/cookbook/controller/error_pages.html有足够的信息可以帮助您入门.
简而言之,您应该创建app/Resources/TwigBundle/views/Exception/exception.json.twig,并且您可以访问exception.message和error_code.
这里有适合您的解决方案:
{% spaceless %}
{
"error":{
"code": {{ error_code }},
"message":{{ exception.message }}
}
}
{% endspaceless %}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用Exception Listener:
namespace Your\Namespace;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class JsonExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$data = array(
'error' => array(
'code' => $exception->getCode(),
'message' => $exception->getMessage()
)
);
$response = new JsonResponse($data, $exception->getCode());
$event->setResponse($response);
}
}
Run Code Online (Sandbox Code Playgroud)
更新您的服务配置:
json_exception_listener:
class: Your\Namespace\JsonExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }
Run Code Online (Sandbox Code Playgroud)
干杯
| 归档时间: |
|
| 查看次数: |
7410 次 |
| 最近记录: |