我有几种使用djangular远程方法调用的方法。
目前当其中一个失败时,我只返回一个带有错误属性的dict / json,如果我的应用程序在JavaScript端检查它。
@allow_remote_invocation
def do_a_thing(self):
return {'error':'oops', 'description':'the thing broke'}
这很好,但偶尔这个方法会超出Python的控制范围,我需要在JavaScript端使用error_callback。
我最终复制了错误处理,这让我在晚上哭了。
function call_the_thing(){
djangoRMI.do_a_thing().then(function(data){
if(data.error){
handleError(data.error)
}else{
....
}
},function(rejectReason){
handleError(rejectReason)
}
}
我当天想到的是,必须有一种从python方面返回和出错的方法,而不仅仅是错误数据的成功。
我希望我可以在HttpResponseServerError
中使用python dict包装,但是我无法理解如何做更多的事情而不是返回字符串,也不知道如何使用Djangular。
这是返回服务器错误的正确方法(如HttpResponseServerError
)吗?或者因为djangular我需要将它视为一个国家啊我一直在做什么?
n.b。我无法在工作上花费/浪费时间尚未。当我这样做的时候,如果这里的答案不合适,我会自我回答。但我也对什么是好的做法感兴趣添加返回JSON感觉就像一个黑客。
答案 0 :(得分:0)
<强> JSONResponseException 强>
它像普通的django异常一样被抛出,但消息kwarg可以获取JSON内容。它默认为响应状态400,但可以使用另一个kwarg设置。
现在你可以写:
@allow_remote_invocation
def do_a_thing(self):
if not thing.do():
return thing.do()
message = {'error':'oops', 'description':'the thing broke'}
status = 500
raise JSONResponseException(message=message,status=status)