Better way to handle errors in tornado request handler

前端 未结 3 935
星月不相逢
星月不相逢 2021-02-15 17:47

There are two similar handlers: AgeHandler1 and AgeHandler2. In the first one we simply raise a specific exception to return an error message, in the second - we manually return

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-15 17:52

    For large projects, I would try to abstract from error numbers, specially because the definition of the HTTP status codes are not in your scope. As much I remember, there is at least one pair of status codes with problematic semantic. I don't remember which they where.

    But for a larger project I would recommend, that you define your own error categories that you want to support and map those categories to HTTP codes centrally as you need. When you find out later, that you should use a different status code for some error category, you can do it centrally.

    Logically I would try to factor out as much knowledge from the specific handling routine as possible. The exception model of course comes here handy, but similar could be reached with a function call for error handling like:

    ...
    if age < 1 or age > 200:
       return self.errorResult('Wrong age value.', WRONG_VALUE)
    ...
    

    or

    ...
    if age < 1 or age > 200:
       return self.wrongValue('Wrong age value.')
    ...
    

提交回复
热议问题