Step 4: ExceptionController support

When implementing an API it is also necessary to handle exceptions in a RESTful way, while ensuring that no security sensitive information leaks out. This bundle provides an extra controller for that job. Using this custom ExceptionController it is possible to leverage the View layer when building responses for uncaught Exceptions.

当实现一个API时,它也需要实现REST风格的异常处理,以确保没有安全敏感信息被泄露。本功能包为此提供了一个额外的控制器。使用这个自定义的ExceptionController,使得利用视图层创建未捕获异常响应成为可能。


To enable the RestBundle view-layer-aware ExceptionController update the twig section of your config as follows:

为了启用RestBundle视图层感知ExceptionController,需要更新您配置中的twig节的内容,如下所示:

# app/config/config.yml
twig:
    exception_controller: 'FOS\RestBundle\Controller\ExceptionController::showAction'

To map Exception classes to HTTP response status codes an “exception map” maybe configured, where the keys match a fully qualified class name and the valuesare either an integer HTTP response status code or a string matching a class constant of the FOS\Rest\Util\Codes class:

为了将异常类映射到 HTTP 响应状态码,需要配置”exception map”项,该项匹配一个完整的类名,其值可以是HTTP响应状态码的整数值,或者是匹配 FOS\Rest\Util\Codes类中字符串常量:

# app/config/config.yml
fos_rest:
    exception:
        codes:
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
            'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
        messages:
            'Acme\HelloBundle\Exception\MyExceptionWithASafeMessage': true

If you want to display the message from the exception in the content of the response, add the exception to the messages map as well. If not only the status code will be returned.

如果您想显示来自响应内容的异常信息,也可以添加异常信息映射。如果没有的话,将返回状态码。


If you know what status code you want to return you do not have to add a mapping, you can do this in your controller:

如果您知道您要返回的状态码是什么,那么您无须添加映射,您只需要在您的控制器中实现即可:

<?php
class UsersController extends Controller
{
    public function postUserCommentsAction($slug)
    {
        if (!$this->validate($slug)) {
            throw new HttpException(400, "New comment is not valid.");
        }
    }
}

See the following example configuration for more details:

更多细节请参见下面的配置示例:

https://github.com/liip-forks/symfony-standard/blob/techtalk/app/config/config.yml

That was it!

Return to the index or continue reading about Automatic route generation: single RESTful controller.

返回指南页或继续阅读自动路由生成:单REST风格控制器