【问题标题】:Is there a way to return a HttpResponseServerError for a Djangular djangoRMI method call?有没有办法为 Djangular djangoRMI 方法调用返回 HttpResponseServerError ?
【发布时间】:2016-01-06 21:32:56
【问题描述】:

我有几个使用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 端返回和出错的方法,而不仅仅是错误数据的成功。

我希望我可以通过 python dict 将 HttpResponseServerError 包装起来,但我无法理解除了返回字符串之外如何做更多的事情,也无法理解如何使用 Djangular 来实现。

这是返回服务器错误的正确方法(如HttpResponseServerError)吗?还是因为djangular我需要把它当作一个民族来对待啊我一直在做什么?

n.b.我还没有能够在工作上花费/浪费时间。当我这样做时,如果这里没有一个像样的答案,我会自我回答。但我也对什么是好的做法感兴趣,添加返回 JSON 感觉就像是 hack。

【问题讨论】:

    标签: python json django httpresponse djangular


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多