Files
notifications-api/app/v2/errors.py
Martyn Inglis 926b8a60f9 Adds in call to new rate limit method in the redis client
- both V1 and V2 APIs
- Rate limiting wrapped into a new method - check_rate_limiting
	- delegates to the previous daily limit and the new though put limit
- Rate limiting done on key type. Each key has it's own limit (number of requests) and interval (time period of requests)
- Configured in the config. Not done on a per-env basis though could be in the future.
2017-04-24 14:15:08 +01:00

76 lines
2.6 KiB
Python

import json
from flask import jsonify, current_app
from jsonschema import ValidationError
from sqlalchemy.exc import DataError
from sqlalchemy.orm.exc import NoResultFound
from app.authentication.auth import AuthError
from app.errors import InvalidRequest
from app.notifications import SendNotificationToQueueError
class TooManyRequestsError(InvalidRequest):
status_code = 429
message_template = 'Exceeded send limits ({}) for today'
def __init__(self, sending_limit):
self.message = self.message_template.format(sending_limit)
class RateLimitError(InvalidRequest):
status_code = 429
message_template = 'Exceeded rate limit for key type {} of {} requests per {} seconds'
def __init__(self, sending_limit, interval, key_type):
# normal keys are spoken of as "live" in the documentation
# so using this in the error messaging
if key_type == 'normal':
key_type = 'live'
self.message = self.message_template.format(key_type.upper(), sending_limit, interval)
class BadRequestError(InvalidRequest):
status_code = 400
message = "An error occurred"
def __init__(self, fields=[], message=None):
self.fields = fields
self.message = message if message else self.message
def register_errors(blueprint):
@blueprint.errorhandler(InvalidRequest)
def invalid_data(error):
current_app.logger.error(error)
response = jsonify(error.to_dict_v2()), error.status_code
return response
@blueprint.errorhandler(ValidationError)
def validation_error(error):
current_app.logger.exception(error)
return jsonify(json.loads(error.message)), 400
@blueprint.errorhandler(NoResultFound)
@blueprint.errorhandler(DataError)
def no_result_found(e):
current_app.logger.exception(e)
return jsonify(status_code=404,
errors=[{"error": e.__class__.__name__, "message": "No result found"}]), 404
@blueprint.errorhandler(AuthError)
def auth_error(error):
return jsonify(error.to_dict_v2()), error.code
@blueprint.errorhandler(SendNotificationToQueueError)
def failed_to_create_notification(error):
current_app.logger.exception(error)
return jsonify(
status_code=500,
errors=[{"error": error.__class__.__name__, "message": error.message}]), 500
@blueprint.errorhandler(Exception)
def internal_server_error(error):
current_app.logger.exception(error)
return jsonify(status_code=500,
errors=[{"error": error.__class__.__name__, "message": 'Internal server error'}]), 500