简体   繁体   中英

How to avoid messy error handling in Tornado RequestHandler

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?

If you want to perform the same checks in multiple handlers, you can just create a base class:

class BaseHandler(web.RequestHandler):
    def prepare(self):
        id = self.path_args[0]
        status = self.path_args[1]

        try:
            id = int(id)
        except ValueError:
            raise web.HTTPError(400, "Invalid id")
        
        # ... and so on ...

Now, just inherit from this base class and the code will be reused.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM