We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在6-three-rituals-of-exceptions-handling.md中 3. 异常处理不应该喧宾夺主
6-three-rituals-of-exceptions-handling.md
有以下异常处理代码
def upload_avatar(request): """用户上传新头像""" try: avatar_file = request.FILES['avatar'] except KeyError: raise error_codes.AVATAR_FILE_NOT_PROVIDED try: resized_avatar_file = resize_avatar(avatar_file) except FileTooLargeError as e: raise error_codes.AVATAR_FILE_TOO_LARGE except ResizeAvatarError as e: raise error_codes.AVATAR_FILE_INVALID try: request.user.avatar = resized_avatar_file request.user.save() except Exception: raise error_codes.INTERNAL_SERVER_ERROR return HttpResponse({})
建议利用上下文管理器来改善我们的异常处理流程
class raise_api_error: """captures specified exception and raise ApiErrorCode instead :raises: AttributeError if code_name is not valid """ def __init__(self, captures, code_name): self.captures = captures self.code = getattr(error_codes, code_name) def __enter__(self): # 该方法将在进入上下文时调用 return self def __exit__(self, exc_type, exc_val, exc_tb): # 该方法将在退出上下文时调用 # exc_type, exc_val, exc_tb 分别表示该上下文内抛出的 # 异常类型、异常值、错误栈 if exc_type is None: return False if exc_type == self.captures: raise self.code from exc_val return False
为什么突然增加了raise self.code from exc_val 的写法 而上文中没有写成
raise self.code from exc_val
try: avatar_file = request.FILES['avatar'] except KeyError as e: raise error_codes.AVATAR_FILE_NOT_PROVIDED from e
The text was updated successfully, but these errors were encountered:
No branches or pull requests
在
6-three-rituals-of-exceptions-handling.md
中3. 异常处理不应该喧宾夺主
有以下异常处理代码
建议利用上下文管理器来改善我们的异常处理流程
为什么突然增加了
raise self.code from exc_val
的写法而上文中没有写成
The text was updated successfully, but these errors were encountered: