使用 OpenStack Nova 异常

Using OpenStack Nova Exceptions

当我使用 nova.keypairs.create() 并向其传递无效的 public 密钥时,我得到以下信息:

BadRequest: Keypair data is invalid: failed to generate fingerprint (HTTP 400) (Request-ID: req-12bc6440-f042-4687-9ee9-d89e7edc260d)

我尝试执行以下操作,但出于显而易见的原因(这是 OpenStack 的一个特例)它没有用:

try:
    nova.keypairs.create(name=keyname, public_key=key)
except BadRequest:
    raise cherrypy.HTTPError(400, "Invalid public key")

如何在我自己的 try 和 except 语句中使用 OpenStack 特定的异常,例如 BadRequest

您需要导入 nova 包的例外情况。通过 github for the package,您似乎需要执行以下操作:

from nova.exception import *

请注意,您看到的异常实际上是 InvalidKeypair exception, which itself subclasses from exception class InvalidBadRequest 消息只是它的模板文本。

因此,您的完整代码如下所示:

from nova.exception import *
# You can import specific ones if you are confident about them
try:
    nova.keypairs.create(name=keyname, public_key=key)
except InvalidKeypair:
    raise cherrypy.HTTPError(400, "Invalid public key")