python - 在非返回函数中引发重定向

标签 python django error-handling

关闭。这个问题需要details or clarity .它目前不接受答案。












想改进这个问题?通过 editing this post 添加详细信息并澄清问题.

8年前关闭。




Improve this question




我有一个函数不返回,我想通过引发异常进行重定向

我有以下代码:

class RedirectRequired(Exception):

    def __init__(self, url):
        self.url = url

和功能
 def Foo(x):   
     hede = {'hodo':5}

  try:
         hede.get('hodo').get('hede')
  except AttributeError, e:
         logger.error(e.message)
         raise RedirectRequired('/')

但是有错误No exception Supplied .关于重定向或引发如下异常的任何想法?

也有错误。

错误无法提交消息:u'RedirectRequired'
错误无法提交消息:u'RedirectRequired'

最佳答案

问题是 RedirectRequired 的构造函数异常构造一个 RedirectRequired引发它的异常,它构造了 RedirectRequired提出它的异常(exception),这…

每次通过这个无限递归,你记录 e.message ,每次都是相同的消息。

在其中大约 1000 个之后,您将点击 RuntimeError: maximum recursion depth exceeded .

您在这里真正想要的很可能是两件事:RedirectRequired异常类型和 Redirector包装类或 redirect使用它的包装函数。像这样:

class RedirectRequired(Exception):
    pass

class Redirector(object):
    def __init__(self, url):
        self.url = url

        hede = {'hodo':5}
        try:
            hede.get('hodo').get('hede')
        except AttributeError, e:
            logger.error(e.message)
            raise RedirectRequired('/')

现在:
>>> r = Redirector('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __init__
__main__.RedirectRequired: /

关于python - 在非返回函数中引发重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20132947/

相关文章:

python - 根据文本将值从一个数据帧平均分配到另一个数据帧

python - 是否可以在不安装的情况下运行 Python(不使用像 py2exe 这样的打包程序)?

python - 涉及 "AttributeError: ' 的奇怪错误 NoneType' 对象没有属性 'append' "

Java Play 框架和 Python Django GAE

Angular 6 : Observable async binding not working as expected after HttpErrorResponse

c# - 在循环中捕获异步错误

python - 多处理池是否为每个进程提供相同数量的任务,或者它们是否被分配为可用?

python - Django 错误 TypeError at/admin/'set' 对象不可逆

python - Django - 选择对象时出错 : "ProgrammingError: operator does not exist: character varying = integer)

php - 在 PHP 中处理 Soap 超时