如何在python/Django中处理错误函数

2024-06-16 12:42:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和django的新手,现在我正在尝试开发人脸识别api,我发现了一个错误,下面是错误日志:https://gist.github.com/wahyu-handayani/9d8338741ee50697332f7ed63f9769e2 当这个错误发生时,服务器将关闭,所以我只想在postman中抛出或返回一些东西,这样服务器仍将打开。到目前为止,我一直在做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


Tags: thedjangohttpsgithub服务器comapi错误
1条回答
网友
1楼 · 发布于 2024-06-16 12:42:45

快速修复方法可以是

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

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 %}

因此,您的服务器不会停机,您可以继续处理该网页

相关问题 更多 >