【问题标题】:FosRestbundle force content-type for error messagesFosRestbundle 强制错误消息的内容类型
【发布时间】:2013-12-17 23:06:46
【问题描述】:
我正在寻找一个简单、愚蠢的解决方案来强制将content-type 转换为application/json 以处理fosrestbundle 中的所有symfony2 http 错误消息(如MethodNotAllowedHttpException 等) .
请求标头示例:
Content-Type: application/x-www-form-urlencoded
Accept: */*
当前响应标头 (MethodNotAllowedHttpException):
Content-Type: text/html; charset=UTF-8
【问题讨论】:
标签:
symfony2
fosrestbundle
php
http
symfony
http-status-codes
fosrestbundle
【解决方案1】:
如果标头中的值未通过逻辑测试,您可以抛出错误。然后在你的 catch 语句中,返回一个 json 响应。像这样的东西(未经测试的代码)
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
// .....
public function myAction(Request $request){
try{
// ...
$cType = $request->headers->get('Content-Type');
// logic for testing if the content type is allowed
if(!in_array($cType,$allowedArray)){
throw new MethodNotAllowedHttpException();
}
// .....
}catch(\Exception $e){
if(get_class($e) == "MethodNotAllowedHttpException"){
$data = array("success"=>false,"message"=>"Method not allowed")
return new JsonResponse($data);
}
}
}
这样你可以用不同的方式处理不同的异常。我不确定它是否是您要用来确定是否抛出异常的内容类型,但您可以使用 $request->headers->get()
获取任何标头信息