Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在webapp2中JSON格式化HTTP错误响应_Json_Google App Engine_Error Handling_Webapp2 - Fatal编程技术网

如何在webapp2中JSON格式化HTTP错误响应

如何在webapp2中JSON格式化HTTP错误响应,json,google-app-engine,error-handling,webapp2,Json,Google App Engine,Error Handling,Webapp2,我使用webapp2在appengine中进行开发。我想做的是在出现错误时发送一个自定义JSON格式的响应。例如,当请求长度大于阈值时,使用HTTP 400和响应体进行响应 {'error':'InvalidMessageLength'} 在webapp2中,可以为某些异常分配错误处理程序。例如: app.error_handlers[400] = handle_error_400 其中,handle_error_400如下所示: def handle_error_400(request,

我使用webapp2在appengine中进行开发。我想做的是在出现错误时发送一个自定义JSON格式的响应。例如,当请求长度大于阈值时,使用HTTP 400和响应体进行响应

{'error':'InvalidMessageLength'}
在webapp2中,可以为某些异常分配错误处理程序。例如:

app.error_handlers[400] = handle_error_400
其中,handle_error_400如下所示:

def handle_error_400(request, response, exception):
    response.write(exception)
    response.set_status(400)
当执行
webapp2.RequestHandler.abort(400)
时,执行上述代码


如何根据上述设置动态地使用不同的响应格式(HTML和JSON)?也就是说,如何调用不同版本的
handle\u error\u 400
函数?

这里有一个完整的工作示例,演示如何对所有类型的错误使用相同的错误处理程序,如果URL以
/json
开头,那么响应将是
应用程序/json
(想象一下如何充分利用
请求
对象来决定应该提供什么样的响应):

在上面的示例中,您可以通过查看以下URL轻松测试不同的行为,这些URL将返回
404
,这是最容易测试的错误:

http://localhost:8080/404
http://localhost:8080/json/404

非常感谢您的回复!@ThanosMakris非常欢迎您。此外,如果您正在启动一个新项目,您可以查看我的项目,在那里您可以看到action JSON()、错误处理(or)和更多的优点。如果您有任何问题,我们非常感谢您的反馈,您也可以用希腊文给我:)请考虑将应用程序移植到GAE init分支中。一旦Lipis形成了框架,我们就移植了所有的项目。事实上,昨天我把wepapp从公司运了过来。灵活性、可维护性和最佳性绝对值得花时间,至少是调查一下。你已经遇到的问题,或者你长大后可能面临的问题,已经解决;)
http://localhost:8080/404
http://localhost:8080/json/404