gpt4 book ai didi

php - FosRestbundle 强制错误消息的内容类型

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:09:40 24 4
gpt4 key购买 nike

我正在寻找一个简单、愚蠢的解决方案来强制所有content-typeapplication/json 中的 http 错误消息(如 MethodNotAllowedHttpException 等)。

示例请求 header :

Content-Type: application/x-www-form-urlencoded 
Accept: */*

当前响应 header (MethodNotAllowedHttpException):

Content-Type: text/html; charset=UTF-8 

最佳答案

如果 header 中的值未通过您的逻辑测试,您可以抛出错误。然后在你的 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() 获取任何 header 信息。

关于php - FosRestbundle 强制错误消息的内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20646503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com