gpt4 book ai didi

python - 根据错误显示定制的异常消息

转载 作者:行者123 更新时间:2023-11-29 11:08:33 25 4
gpt4 key购买 nike

我希望我的代码显示一条自定义错误消息,该消息取决于它遇到的错误类型。

from .forms import NameForm, IdForm
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import messages
from client_storage import insert
import mysql.connector.errors
from mysql.connector.errors import Error
import MySQLdb


def sign_in(request):
#we need to handle all the data that was just typed, we'll add a condition for that
if request.method == "POST":
#here will construct the form with the POST data
form = NameForm(request.POST)
#the next part is to check that the information submitted is valid
if form.is_valid():
post = form.save()
post.save()
return HttpResponse(post.question_text)
else:
return HttpResponse("Form is invalid")
else:
form = NameForm()
return render(request, 'checkin/base.html', {'form': form})

#this view will be the sign-up view, where new clients will be given new ID numbers for training

def sign_up(request):

if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
#we'll call an external function that checks membership of the users input in the database
# query is the first element of the tuple that is returned from insert()
query = insert(post.id_text)
if query == 1062:
messages.add_message(request, messages.INFO, 'Already taken ')
return HttpResponseRedirect('sign_up')
if query == 1054:
messages.add_message(request, messages.INFO, 'Invalid input')
return HttpResponseRedirect('sign_up')
else:
messages.add_message(request, messages.INFO, 'Thank you for signing up!')
return HttpResponseRedirect('sign_up')

# if the user enters a number that is already in use raise an 'duplicate' error
# Capture the exception here
else:
return HttpResponse('That text is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})

For the `except` block I'm trying to figure out how to display either "Already taken" or "Invalid input" depending on the error code. However only "Already taken" ever appears. I feel like the problem is that the exception is being thrown before it even gets to the `if` clauses?

我正在使用另一个文件进行 INSERT 过程:

import MySQLdb
import mysql.connector
from mysql.connector import errorcode
from django.contrib import messages

#Use a function to insert new information into the database

def insert(info):
#open a connection
db = MySQLdb.connect('localhost','root','password', 'CLIENTS')
#prepare a cursor
cursor = db.cursor()
#prepare SQL query
sql = "INSERT INTO clients(ID) VALUES (%s)" % info

try:
#execute the command
cursor.execute(sql)
#commit changes to the database
print 'success'
db.commit()
except MySQLdb.Error as e:
#return the first element in the tuple that contains the error message, which will be the errorcode
if e[0] == 1062:
return e[0]
if e[0] == 1054:
return e[0]

#disconnect from server
db.close()

编辑问题似乎是我使用mysql.connector.error而不是MySQLdb.Error mysql网站似乎只使用前者。似乎关于后者的官方文档并不多,但幸运的是我找到了 this site.我更改了代码,以便 sign_in View 将从外部 insert 函数接收返回的信息,然后采取相应的操作。

最佳答案

就像 @wwii 在评论中所说的那样,您需要编辑 try ... except block 才能捕获异常。请参阅documentations的此页.

此外,在您的实际代码中 Error(errno=1062) 始终返回一个非零字符串,该字符串验证您的 if 语句。这就是为什么您总是收到已采取消息的原因。

为了解决这个问题,您应该将代码修改为如下示例:

# What you need to import
import mysql.connector
from mysql.connector import errorcode

try:
insert(post.id_text)
messages.add_message(request, messages.INFO, 'Thank you for signing up ')
return HttpResponseRedirect('sign_in')

# Catch the error exception
except mysql.connector.Error as err:
# Error code 1062: https://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_dup_entry
if err.errno == errorcode.ER_DUP_ENTRY:
messages.add_message(request, messages.INFO, "Already taken")
return HttpResponseRedirect('sign_up')

# Error code 1054: https://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_bad_field_error
if err.errno == errorcode.ER_BAD_FIELD_ERROR:
messages.add_message(request, messages.INFO, "Invalid input")
return HttpResponseRedirect('sign_up')

编辑:

您编辑的答案在 Python2Python3 中都是正确的。

否则,如果您使用的是Python2,您可以执行类似的操作。

try:
#execute the command
cursor.execute(sql)
#commit changes to the database
print 'success'
db.commit()
except MySQLdb.Error, e:
if e.args[0] == 1062 or e.args[0] == 1054:
# e.args[0] is the error code in int format
# e.args[1] is the complete error message in str format
return e.args[1]
else:
# I didn't test all the cases, but this message
# can save you more time during the debug later
# if your code catch another error code rather than 1062 or 1054
return "Something odd happened"

您也可以执行类似的操作(此示例如果对 Python2Python3 均有效):

try:
#execute the command
cursor.execute(sql)
#commit changes to the database
print 'success'
db.commit()
except MySQLdb.Error as e:
if e[0] == 1062 or e[0] == 1054:
# e[0] is the error code in int format
# e[1] is the complete error message in str format
return e[1]
else:
# Good for the debug
return "Something odd happened"

关于python - 根据错误显示定制的异常消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com