【问题标题】:How to handle error function in python / django如何在 python / django 中处理错误函数
【发布时间】:2021-06-13 07:46:51
【问题描述】:

我是 python 和 django 的新手,现在我正在尝试开发人脸识别 api,但出现错误,这是错误日志:https://gist.github.com/wahyu-handayani/9d8338741ee50697332f7ed63f9769e2 当该错误发生时,服务器将关闭,所以我只想在邮递员中抛出或返回一些东西,以便服务器仍然开启。到目前为止我一直在做tryexcept

try:
        # some codes
        cv2.imshow('Frame', image) # here is the code that makes the error happens
        
except Exception as e:
        return JsonResponse({"Error": str(e)})

但仍然......它不会进入Exception 块。如何在函数中为tryexcept做正确的方法?

【问题讨论】:

    标签: python django function error-handling


    【解决方案1】:

    可以快速解决,

    在模板中创建一个默认错误页面,并在出现异常时显示该页面

    def anyfunction(request):
        try:
            #some code
        except:
            context = {
                'error' : "Error  message of that page !"
            }
            return render(request, 'error/errorpage.html',context)
    

    errorpage.html 是一个显示错误的模板:

    <!DOCTYPE html>
    {% extends "base.html" %}
    {% load static %}
    
    {% block title %}
    
    Error !
    
    {% endblock %}
    
    {% block body %}
    
    <h1>oops Page error!!!</h1>
    <br>
    <div class="jumbotron">
        {{error}}
    </div>
    
    {% endblock %}
    

    因此您的服务器不会关闭,您可以继续在网页上工作

    【讨论】:

    • 谢谢@SANGEETHSUBRAMONIAM,我已经尝试过你的代码,但是当我添加此代码cv2.imshow('Frame', image) 时服务器仍然关闭,但是当我删除tahat 代码并更改为raise Exception("err") 时,我得到了邮递员的回复就像您的回答一样,并且服务器仍在运行..有没有办法从cv2.imshow('Frame', image)捕获未捕获的错误@
    • 我认为错误发生在命中 try-except 块之前。
    • @Martins 我试过添加cv2.imshow('Frame', image)后出现错误,因为当我删除这行代码时,程序仍然运行良好
    猜你喜欢
    • 2021-07-20
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多