You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.0 KiB
Python

# -*- coding: utf-8 -*-
import logging
from tornado import escape
from tornado.web import HTTPError
# HTTP status code
HTTP_OK = 200
ERROR_BAD_REQUEST = 400
ERROR_UNAUTHORIZED = 401
ERROR_FORBIDDEN = 403
ERROR_NOT_FOUND = 404
ERROR_METHOD_NOT_ALLOWED = 405
ERROR_INTERNAL_SERVER_ERROR = 500
# Custom error code
ERROR_WARNING = 1001
ERROR_DEPRECATED = 1002
ERROR_MAINTAINING = 1003
ERROR_UNKNOWN_ERROR = 9999
ERROR_LICENSE_NOT_ACTIVE = 9000
ERROR_LICENSE_EXPIRE_ATALL = 9003
class HTTPAPIError(HTTPError):
"""API error handling exception
API server always returns formatted JSON to client even there is
an internal server error.
"""
def __init__(self, status_code=ERROR_UNKNOWN_ERROR, message=None,
error=None, data=None, log_message=None, *args):
assert isinstance(data, dict) or data is None
message = message if message else ""
assert isinstance(message, str)
super(HTTPAPIError, self).__init__(int(status_code),
log_message, *args)
self.error = error if error else \
_error_types.get(self.status_code, _unknow_error)
self.message = message
self.data = data if data is not None else {}
def __str__(self):
err = {"meta": {"code": self.status_code, "error": self.error}}
if self.data:
err["data"] = self.data
if self.message:
err["meta"]["message"] = self.message
return escape.json_encode(err)
# default errors
_unknow_error = "unknow_error"
_error_types = {400: "bad_request",
401: "unauthorized",
403: "forbidden",
404: "not_found",
405: "method_not_allowed",
500: "internal_server_error",
1001: "warning",
1002: "deprecated",
1003: "maintaining",
9000: "license_not_active",
9003: "license_expire_at_all",
9999: _unknow_error}