|
| 1 | +"""Structured JSON error responses for API routes.""" |
| 2 | + |
| 3 | +from flask import jsonify, make_response, request |
| 4 | +from marshmallow import ValidationError as MarshmallowValidationError |
| 5 | +from sqlalchemy.exc import SQLAlchemyError |
| 6 | + |
| 7 | +from mod_api import mod_api |
| 8 | + |
| 9 | +_API_PREFIX = '/api/v1' |
| 10 | + |
| 11 | + |
| 12 | +def make_error_response(code, message, details=None, http_status=400): |
| 13 | + """Build a JSON error response conforming to the ErrorResponse schema.""" |
| 14 | + body = { |
| 15 | + 'code': code, |
| 16 | + 'message': str(message)[:500], |
| 17 | + 'details': details if details is not None else {}, |
| 18 | + } |
| 19 | + response = jsonify(body) |
| 20 | + response.status_code = http_status |
| 21 | + return response |
| 22 | + |
| 23 | + |
| 24 | +@mod_api.errorhandler(400) |
| 25 | +def handle_400(error): |
| 26 | + """Bad request.""" |
| 27 | + return make_error_response( |
| 28 | + 'validation_error', |
| 29 | + getattr(error, 'description', 'Bad request.'), |
| 30 | + http_status=400, |
| 31 | + ) |
| 32 | + |
| 33 | + |
| 34 | +@mod_api.errorhandler(401) |
| 35 | +def handle_401(error): |
| 36 | + """Unauthorized.""" |
| 37 | + return make_error_response( |
| 38 | + 'unauthorized', |
| 39 | + 'Bearer token is missing, expired, or invalid.', |
| 40 | + http_status=401, |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +@mod_api.errorhandler(403) |
| 45 | +def handle_403(error): |
| 46 | + """Forbidden.""" |
| 47 | + return make_error_response( |
| 48 | + 'forbidden', |
| 49 | + 'Token does not have the required scope for this operation.', |
| 50 | + http_status=403, |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +@mod_api.errorhandler(404) |
| 55 | +def handle_404(error): |
| 56 | + """Not found.""" |
| 57 | + return make_error_response( |
| 58 | + 'not_found', |
| 59 | + getattr(error, 'description', 'Resource not found.'), |
| 60 | + http_status=404, |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +@mod_api.errorhandler(405) |
| 65 | +def handle_405(error): |
| 66 | + """Handle method-not-allowed errors for API routes.""" |
| 67 | + resp = make_error_response( |
| 68 | + 'method_not_allowed', |
| 69 | + 'Method not allowed.', |
| 70 | + http_status=405, |
| 71 | + ) |
| 72 | + if hasattr(error, 'valid_methods') and error.valid_methods: |
| 73 | + resp.headers['Allow'] = ', '.join(error.valid_methods) |
| 74 | + return resp |
| 75 | + |
| 76 | + |
| 77 | +@mod_api.errorhandler(422) |
| 78 | +def handle_422(error): |
| 79 | + """Unprocessable entity.""" |
| 80 | + return make_error_response( |
| 81 | + 'unprocessable', |
| 82 | + getattr( |
| 83 | + error, |
| 84 | + 'description', |
| 85 | + 'Request is valid JSON but semantically invalid.'), |
| 86 | + http_status=422, |
| 87 | + ) |
| 88 | + |
| 89 | + |
| 90 | +@mod_api.errorhandler(429) |
| 91 | +def handle_429(error): |
| 92 | + """Rate limited.""" |
| 93 | + return make_error_response( |
| 94 | + 'rate_limited', |
| 95 | + 'Rate limit exceeded.', |
| 96 | + details={'retry_after': 30, 'limit': 120, 'window': '60s'}, |
| 97 | + http_status=429, |
| 98 | + ) |
| 99 | + |
| 100 | + |
| 101 | +@mod_api.errorhandler(500) |
| 102 | +def handle_500(error): |
| 103 | + """Handle unexpected server errors for API routes.""" |
| 104 | + return make_error_response( |
| 105 | + 'internal_error', |
| 106 | + 'An unexpected error occurred.', |
| 107 | + http_status=500, |
| 108 | + ) |
| 109 | + |
| 110 | + |
| 111 | +@mod_api.errorhandler(MarshmallowValidationError) |
| 112 | +def handle_marshmallow_validation_error(error): |
| 113 | + """Catch schema validation failures and return them as 400.""" |
| 114 | + return make_error_response( |
| 115 | + 'validation_error', |
| 116 | + 'Request failed schema validation.', |
| 117 | + details={'fields': error.messages}, |
| 118 | + http_status=400, |
| 119 | + ) |
| 120 | + |
| 121 | + |
| 122 | +@mod_api.errorhandler(SQLAlchemyError) |
| 123 | +def handle_sqlalchemy_error(error): |
| 124 | + """Log database errors.""" |
| 125 | + from flask import g |
| 126 | + log = getattr(g, 'log', None) |
| 127 | + if log: |
| 128 | + log.error(f'Database error in API: {type(error).__name__}') |
| 129 | + return make_error_response( |
| 130 | + 'internal_error', |
| 131 | + 'An unexpected database error occurred.', |
| 132 | + http_status=500, |
| 133 | + ) |
| 134 | + |
| 135 | + |
| 136 | +@mod_api.after_app_request |
| 137 | +def convert_api_errors_to_json(response): |
| 138 | + """Catch routing errors that were handled by global app handlers and convert them to JSON.""" |
| 139 | + if request.path.startswith(_API_PREFIX): |
| 140 | + if response.status_code == 404: |
| 141 | + return make_error_response('not_found', 'Resource not found.', http_status=404) |
| 142 | + if response.status_code == 405: |
| 143 | + return make_error_response('method_not_allowed', 'Method not allowed.', http_status=405) |
| 144 | + return response |
0 commit comments