Error handling 在web2py的数据库备份视图中检查有效/现有id的标准代码是什么?

Error handling 在web2py的数据库备份视图中检查有效/现有id的标准代码是什么?,error-handling,web2py,http-error,Error Handling,Web2py,Http Error,在web2py中,假设我有以下url: www.example.com/customer/view/1 它由customer控制器中的view() 在视图函数中,我希望处理以下错误情况: 未传递任何参数(/customer/view/)->raise 404 传递了一个非整数参数(/customer/view/apple)->raise 404 传递了一个整数参数,但该参数在数据库中不存在(/customer/view/999999)->raise 404 出现应用程序错误,例如无法连接到数据库

在web2py中,假设我有以下url:

www.example.com/customer/view/1

它由
customer
控制器中的
view()

视图
函数中,我希望处理以下错误情况:

  • 未传递任何参数(
    /customer/view/
    )->raise 404
  • 传递了一个非整数参数(
    /customer/view/apple
    )->raise 404
  • 传递了一个整数参数,但该参数在数据库中不存在(
    /customer/view/999999
    )->raise 404
  • 出现应用程序错误,例如无法连接到数据库->引发500异常
  • 在控制器函数中,以返回正确HTTP错误的方式处理这些情况的标准/规范/正确方法是什么?这是一个非常常见的场景,我希望每次都能以正确和简洁的方式进行

    除了不区分id无效/现有错误和任何其他错误外,这几乎可以正常工作:

    def view():
        try:
            customer = db(db.customer.id==request.args(0, cast=int)).select()[0]
        except:
            raise HTTP(404, 'Cannot find that customer')
    
        return dict(customer=customer)
    
    如果cast在request.args()中失败,默认情况下它将引发自己的HTTP(404),但您无法控制消息。因此,在这种情况下,您可以使用
    否则
    参数返回
    None
    。如果arg缺失或非整数,或者数据库中未找到客户,则数据库查询将返回
    None

    def view():
        id = request.args(0, cast=int, otherwise=lambda: None)
        customer = db(db.customer.id == id).select().first()
        if not customer:
            raise HTTP(404, 'Cannot find that customer' if id
                       else 'Missing/invalid customer ID')
        return dict(customer=customer)