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.


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


# app/config/config.yml
    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
            'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
            'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
            '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:


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:


That was it!

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