后端发送数据结构设计
数据结构
后端发送数据结构 """ code:状态码,判断数据状态 error:错误信息,数据校验失败,后端主动发送的错误信息 data:数据校验成功后,发送的有用信息 """ { code:1001 error:'' data:'' }
代码
class BaseResponse(object): def __init__(self,): self.code=1000 self.data="" self.error="" @property def dict(self): return self.__dict__
异常数据处理
异常:自带的异常
自定义异常
自定义异常代码:
class PricePolicyError(Exception): def __init__(self): self.error = '价格策略不存在' class CommonException(Exception): def __init__(self,error,code = 1100): self.error =error self.code = code
处理方式:
异常信息处理方式:
主动抛出异常
捕获异常
定义状态码,和错误信息
代码:
res = BaseResponse() # 自定义的数据结构 try: xx == oo if not xx: raise 自定义异常1(code,error) exception 项目自己抛出的异常(需要模块导入)as e: res.code = xxxx res.error = xxxx exception 自定义的异常(需要模块导入)as e: res.code = e.code res.error = e.error
正常数据处理
res.data = 要发送的数据