FOSRestBundle功能包:异常控制器支持

RESTful API异常处理
本文介绍如何在RESTful API中采用安全的方式处理异常,并通过配置文件实现不同异常类与HTTP状态码之间的映射,同时提供了自定义ExceptionController的方法。

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节的内容,如下所示:

1
2
3
# 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类中字符串常量:

1
2
3
4
5
6
7
8
# 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:

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

1
2
3
4
5
6
7
8
9
10
<?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风格控制器




本文转自 firehare 51CTO博客,原文链接:http://blog.51cto.com/firehare/1253458,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值