130 lines
3.2 KiB
Python
130 lines
3.2 KiB
Python
# 异常
|
|
|
|
# 具体的异常捕获
|
|
try:
|
|
with open("abc.text", "r") as f:
|
|
data = f.read()
|
|
except FileNotFoundError:
|
|
print("文件不存在")
|
|
except PermissionError:
|
|
print("没有权限")
|
|
except OSError:
|
|
print("系统错误")
|
|
|
|
# 避免空的except块
|
|
# try:
|
|
# risky_operation()
|
|
# except SpecificError as e:
|
|
# logger.error(f"操作失败", e)
|
|
# # 或者采取其他的操作
|
|
|
|
# 资源清理
|
|
# with open("abc.txt", "r") as f:
|
|
# data = f.read()
|
|
# process_data(data)
|
|
|
|
|
|
# 异常日志记录
|
|
import logging
|
|
|
|
# 配置日志模块
|
|
logging.basicConfig(level=logging.ERROR)
|
|
|
|
|
|
# 数据库报错
|
|
class DataBaseError(Exception):
|
|
pass
|
|
|
|
|
|
# 校验用户数据是否有效
|
|
class ValidationError(Exception):
|
|
pass
|
|
|
|
|
|
# 根据id从数据库中查询数据
|
|
def get_user_from_db(user_id):
|
|
if user_id == 0:
|
|
raise DataBaseError("数据库连接失败")
|
|
return {"user_id": user_id, "user_name": "小明", "age": 20}
|
|
|
|
|
|
# 校验拿到的当前用户信息是否合法
|
|
def validate_and_process(user_data):
|
|
if not user_data["user_name"] or user_data["age"] < 0:
|
|
raise ValidationError("用户信息无效")
|
|
user_data["process"] = True
|
|
return user_data
|
|
|
|
|
|
def process_user_data(user_id):
|
|
try:
|
|
user_data = get_user_from_db(user_id)
|
|
result = validate_and_process(user_data)
|
|
return result
|
|
except DataBaseError as e:
|
|
logging.error(f"数据库错误-用户ID:{user_id},错误{e}")
|
|
raise
|
|
except ValidationError as e:
|
|
logging.error(f"用户信息错误,用户ID{user_id},错误{e}")
|
|
return None
|
|
except Exception as e:
|
|
logging.critical(f"未知错误,用户ID{user_id},错误{e}")
|
|
raise
|
|
|
|
|
|
# result = process_user_data(0)
|
|
# print(result)
|
|
|
|
|
|
# 数据验证
|
|
class DataValidator:
|
|
|
|
@staticmethod
|
|
def validate_email(email):
|
|
if not isinstance(email, str):
|
|
raise TypeError("邮箱必须是字符串")
|
|
if "@" not in email:
|
|
raise ValueError("无效的邮箱格式")
|
|
return email.lower()
|
|
|
|
@staticmethod
|
|
def validate_age(age):
|
|
if not isinstance(age, int):
|
|
raise TypeError("年龄必须是整数")
|
|
if age < 0 or age > 160:
|
|
raise ValueError("年龄必须在0~160之间")
|
|
return age
|
|
|
|
def validate_user_data(user_data):
|
|
error = {}
|
|
try:
|
|
user_data["email"] = DataValidator.validate_email(user_data["email"])
|
|
except (TypeError, ValueError) as e:
|
|
error["email"] = str(e)
|
|
|
|
try:
|
|
user_data["age"] = DataValidator.validate_age(user_data["age"])
|
|
except (TypeError, ValueError) as e:
|
|
error["age"] = str(e)
|
|
if error:
|
|
raise ValidationError("数据验证失败", error)
|
|
|
|
|
|
class ValidationError(Exception):
|
|
def __init__(self, message, errors):
|
|
self.message = message
|
|
self.errors = errors
|
|
super().__init__(self.message)
|
|
|
|
|
|
# 测试用例
|
|
user_input = {"email": "invalid-email", "age": 200}
|
|
|
|
try:
|
|
validate_data = DataValidator.validate_user_data(user_input)
|
|
print(f"数据验证成功,{validate_data}")
|
|
except ValidationError as e:
|
|
print(f"数据验证失败{e.message}")
|
|
for field, error in e.errors.items():
|
|
print(f"{field}:{error}")
|