Python 自定义异常处理

标签 python custom-exceptions

经过多次谷歌搜索以弄清楚发生了什么,这里是:

我有一个需要请求和响应的自定义验证异常

class ValidationException(Exception):
    message = "Caught Validation Exception"

    def __init__(self, request, response):
        self.details = {
            "request": request,
            "response": response
        }
        super(ValidationException, self).__init__(self.message, self.details)

我有一个异常处理程序,它将在某些条件下引发它的实例:

class handler:
    if something:
        raise ValidationException(request, response)

如果我们在帖子中遇到问题,则会调用处理程序

class Poster:
    def post(data):
        if self.last_response.status_code not in self.valid_post_codes:
            self.exception_handler.handleException(self.last_request, self.last_response)

问题是,我正在引发 ValidationException,将其放入我的回溯中,但是,它似乎没有在我想要的地方捕获。

def testThis(self):
    try:
        self.poster.post(json.dumps({}))
    except ValidationException:
        print "got validation"
    except Exception:
        print "got exception"

结果:“出现异常”

回溯

lib/service/pas/api/order.py line 24 in postOrder
  return self.post()
lib/service/base.py line 42 in post
  self.exception_handler.handleException(self.last_request, self.last_response)
lib/service/exception/handler.py line 14 in handleException
  raise ValidationException(request, response)
ValidationException:

它的值(value):

assertRaises(ValidationException, self.poster.post, json.dumps({}))

也仅捕获异常。有任何想法吗? :\任何帮助是极大的赞赏!提前致谢

最佳答案

好吧好吧...所以..

我的 IDE 在导入时添加了“lib”前缀,该前缀导入了 Exceptions.ValidationException。

当我在其他地方抛出 my.own.ValidationException 时,它没有被捕获,因为它不是同一类型。结果碰巧出现了另一个我不知道的 ValidationException...

太棒了,不是!

关于Python 自定义异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26662240/

相关文章:

c# - 对自定义异常进行单元测试

python - 在 Windows 上使用 Python 2.6 的 mod_python

python - 通过 post 请求将二进制数据作为文件提交

python - 如何编写无需退出应用程序即可 self 更新的python代码?

java - 我无法让我的方法抛出自定义异常

python - Django 模型 : Filtering by user, 始终

python - 如何使用 Django Admin 注册自定义表单

php - 获取 Laravel 异常的模型

c# - 什么时候最好不要创建用户定义的异常?