异常处理程序作为函数

时间:2014-03-26 08:52:35

标签: python exception-handling tornado

我正在使用龙卷风来创建一个休息处理程序..这里我有一些常见的例外,如InvalidRequest,InvalidToken等。所以我想知道我如何为这些创建一种超级异常处理程序并处理其余的函数本身..示例代码的一部分

class RestRegisterHandler(RestHandler):
@gen.coroutine
def post(self):
    self.raw_data = None
    try:
        yield self.validate_user()
        self.raw_data = json_decode(self.request.body)
        logger.debug(self.raw_data)
        model_object = self.model(self.raw_data)
        model_object.validate()
        logger.debug("Inseting to database")
        yield model_object.insert(self.db)
    except InvalidRequest:
        self.write_error(404, 'Invalid request')
    except InvalidToken:
        self.write_error(404, 'Token Validation Failed')
    except ModelValidationError as error:
        logger.error("Unknown Validation error: '{0}'".format(error))
        raise utils.errors.ValidationError(400, error_messages=error.messages)
    except DuplicateKeyError:
        logger.debug("User already exists")
        self.write_error(404, 'User already exists')
    except Exception as e:
        logger.error(e)
        self.write_error(404, 'Invalid request')
    else:
        logger.debug("db saved")
        self.write("Registered succesfully")
        return

这样的东西
class RestHandler():
  def super_exception():
    except InvalidToken:
        print()
    except InvalidRequest:
        print()
    # the rest of exceptions should be handled by post function

2 个答案:

答案 0 :(得分:0)

这样的东西?

class RestHandler(object):
    # "default" exception handling in the super class
    def handle_exception(self, e):
        logger.error('Default error handling caught a "%s"' % e)

class RestRegisterHandler(RestHandler):
    # "specific" exception handling in the child class
    def handle_exception(self, e):
        # Just an idea, you can implement this in different ways
        WRITE_ERROR             = (InvalidRequest, InvalidToken, DuplicateKeyError)
        WRITE_ERROR_WITH_LOGGER = (Exception,)
        RAISE_VALIDATION_ERROR  = (ModelValidationError,)

        if e in WRITE_ERROR:
            self.write_error(404, str(e))
        elif e in WRITE_ERROR_WITH_LOGGER:
            logger.error(e)
            self.write_error(404, str(e))
        elif e in RAISE_VALIDATION_ERROR:
            logger.error("Unknown Validation error: '{0}'".format(e))
            raise utils.errors.ValidationError(400, error_messages=e.messages)
        else:
            # if couldn't be handled here, fallback to the default implementation
            super(RestHandler, self).handle_exception(e)        


    @gen.coroutine
    def post(self):
        self.raw_data = None
        try:
            yield self.validate_user()
            self.raw_data = json_decode(self.request.body)
            logger.debug(self.raw_data)
            model_object = self.model(self.raw_data)
            model_object.validate()
            logger.debug("Inseting to database")
            yield model_object.insert(self.db)

        except Exception as e:
            self.handle_exception(e)

        else:
            logger.debug("db saved")
            self.write("Registered succesfully")
            return

答案 1 :(得分:0)

对此的一般解决方案是覆盖RequestHandler.write_error(并且不要自己调用write_error,只是让错误逃脱处理函数)。 write_error将获得exc_info关键字参数,该参数可让您查看导致请求失败的异常。