如何避免在龙卷风请求中处理混乱的错误处理
假设我有一个像这样的简单 RequestHandler
。
class RequestHandler(web.RequestHandler):
def get(self, id, status):
obj = self.retrieve_object(id)
obj.update({"status": status})
self.write(json.dumps(obj))
问题是,每当处理程序中出现错误时,它都会返回错误 500(内部服务器错误)。显然,当用户输入无效内容时,我想返回错误 400。
所以我必须添加一堆错误检查,如下所示:
class RequestHandler(web.RequestHandler):
def get(self, id, status):
try:
id = int(id)
except ValueError:
raise web.HTTPError(400, "Invalid id")
if status not in ("open", "closed"):
raise web.HTTPError(400, "Invalid status")
try:
obj = self.retrieve_object(id)
except ObjDoesntExistError:
raise web.HTTPError(400, "Object doesn't exist")
obj.update({"status": status})
self.write(json.dumps(obj))
问题是这给函数增加了很多膨胀。有没有更干净的方法来做到这一点?或者这是不可避免的?
Say I have a simple RequestHandler
like this.
class RequestHandler(web.RequestHandler):
def get(self, id, status):
obj = self.retrieve_object(id)
obj.update({"status": status})
self.write(json.dumps(obj))
Problem is, whenever there's an error in the handler, it's gonna return an error 500 (Internal server error). Obviously I want to return an error 400 instead when the user has inputted something invalid.
So I have to add a bunch of error checking, like this:
class RequestHandler(web.RequestHandler):
def get(self, id, status):
try:
id = int(id)
except ValueError:
raise web.HTTPError(400, "Invalid id")
if status not in ("open", "closed"):
raise web.HTTPError(400, "Invalid status")
try:
obj = self.retrieve_object(id)
except ObjDoesntExistError:
raise web.HTTPError(400, "Object doesn't exist")
obj.update({"status": status})
self.write(json.dumps(obj))
The issue is that this adds a lot of bloat to the function. Is there a cleaner way to do this? Or is it unavoidable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要在多个处理程序中执行相同的检查,则可以创建一个基类:
现在,只需从该基类继承即可,并且代码将被重复使用。
If you want to perform the same checks in multiple handlers, you can just create a base class:
Now, just inherit from this base class and the code will be reused.