Symfony3中的状态消息处理

时间:2016-03-30 23:22:21

标签: exception symfony

我经常发现Symfony中的控制器类似于以下内容:

interval = 1e-6
threading.Timer( interval, func ).start()

显然这是一个夸张的场景,但基本上我发现我的控制器正在变得错综复杂的长错误/成功消息逻辑。 Symfony是否有更好的方法来处理这种模式,与瘦的控制器范式保持一致?

1 个答案:

答案 0 :(得分:0)

也许ExceptionListener可以在这里帮助你。

来自symfony docs

class ExceptionListener
{
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
    // You get the exception object from the received event
    $exception = $event->getException();
    $message = sprintf(
        'My Error says: %s with code: %s',
        $exception->getMessage(),
        $exception->getCode()
    );

    // Customize your response object to display the exception details
    $response = new Response();
    $response->setContent($message);

    // HttpExceptionInterface is a special type of exception that
    // holds status code and header details
    if ($exception instanceof HttpExceptionInterface) {
        $response->setStatusCode($exception->getStatusCode());
        $response->headers->replace($exception->getHeaders());
    } else {
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    // Send the modified response object to the event
    $event->setResponse($response);
 }
}