def test_url(url):
pattern = r'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$'
return bool(re.match(pattern, url))
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
# exceptions.py
class ValidationError(APIError):
def __init__(self, field: str, **additional_params):
self.field = field
self.additional_params = additional_params
@classmethod
def required(cls, field: str) -> 'ValidationError':
return cls(
field=field,
error_code=ErrorCode.VALIDATION_REQUIRED,
params={"field": field}
)
@classmethod
def invalid_length(cls, field: str, min_length: int, max_length: int) -> 'ValidationError':
return cls(
field=field,
error_code=ErrorCode.VALIDATION_LENGTH,
params={
"field": field,
"min": min_length,
"max": max_length
}
)
@classmethod
def invalid_range(cls, field: str, min_value: int, max_value: int) -> 'ValidationError':
return cls(
field=field,
error_code=ErrorCode.VALIDATION_RANGE,
params={
"field": field,
"min": min_value,
"max": max_value
}
)
# 使用例
def validate_user_data(data: dict):
# 必須チェック
if 'username' not in data:
raise ValidationError.required(field="username")
# 桁数チェック
if len(data['username']) < 3 or len(data['username']) > 50:
raise ValidationError.invalid_length(
field="username",
min_length=3,
max_length=50
)
# 年齢の範囲チェック
if 'age' in data:
if data['age'] < 0 or data['age'] > 150:
raise ValidationError.invalid_range(
field="age",
min_value=0,
max_value=150
)
# error_definitions.py
from enum import Enum
class ErrorCode(Enum):
VALIDATION_ERROR = "E4001"
NOT_FOUND = "E4004"
UNAUTHORIZED = "E4011"
FORBIDDEN = "E4031"
CONFLICT = "E4091"
INTERNAL_ERROR = "E5001"
DATABASE_ERROR = "E5002"
EXTERNAL_API_ERROR = "E5003"
ERROR_MESSAGES = {
ErrorCode.VALIDATION_ERROR.value: "{field}が不正です",
ErrorCode.NOT_FOUND.value: "{resource}が見つかりません",
ErrorCode.UNAUTHORIZED.value: "認証が必要です",
ErrorCode.FORBIDDEN.value: "アクセス権限がありません",
ErrorCode.CONFLICT.value: "{resource}が既に存在します",
ErrorCode.INTERNAL_ERROR.value: "内部エラーが発生しました",
ErrorCode.DATABASE_ERROR.value: "データベースエラーが発生しました",
ErrorCode.EXTERNAL_API_ERROR.value: "外部APIとの通信でエラーが発生しました"
}
# exceptions.py
from typing import Dict, Any, Optional
from .error_definitions import ErrorCode, ERROR_MESSAGES
class APIError(Exception):
"""Base class for API errors"""
status_code = 500
error_code = ErrorCode.INTERNAL_ERROR
def __init__(self,
message: Optional[str] = None,
status_code: Optional[int] = None,
error_code: Optional[ErrorCode] = None,
params: Optional[Dict[str, str]] = None,
payload: Optional[Dict] = None):
super().__init__()
self.error_code = error_code or self.error_code
self.status_code = status_code or self.status_code
self.params = params or {}
self.payload = payload or {}
# メッセージのフォーマット処理
if message:
self.message = message
else:
self.message = ERROR_MESSAGES[self.error_code.value].format(**self.params)
def to_dict(self) -> Dict[str, Any]:
rv = dict(self.payload)
rv.update({
'message': self.message,
'status': self.status_code,
'error_code': self.error_code.value
})
return rv
class ValidationError(APIError):
status_code = 400
error_code = ErrorCode.VALIDATION_ERROR
class NotFoundError(APIError):
status_code = 404
error_code = ErrorCode.NOT_FOUND
class UnauthorizedError(APIError):
status_code = 401
error_code = ErrorCode.UNAUTHORIZED
class ForbiddenError(APIError):
status_code = 403
error_code = ErrorCode.FORBIDDEN
class ConflictError(APIError):
status_code = 409
error_code = ErrorCode.CONFLICT
# exceptions.py
from typing import Dict, Any, Optional
from .error_codes import ErrorCode
from .error_messages import ERROR_MESSAGES
class APIError(Exception):
"""Base class for API errors"""
status_code = 500
error_code = ErrorCode.INTERNAL_ERROR
def __init__(self,
message: Optional[str] = None,
status_code: Optional[int] = None,
error_code: Optional[ErrorCode] = None,
params: Optional[Dict[str, str]] = None,
payload: Optional[Dict] = None):
super().__init__()
self.error_code = error_code or self.error_code
self.status_code = status_code or self.status_code
self.params = params or {}
self.payload = payload or {}
if message:
self.message = message
else:
self.message = ERROR_MESSAGES[self.error_code.value].format(**self.params)
def to_dict(self) -> Dict[str, Any]:
rv = dict(self.payload)
rv.update({
'message': self.message,
'status': self.status_code,
'error_code': self.error_code.value
})
return rv
# 各種エラークラスの定義
# ...
# error_handlers.py
from flask import jsonify, current_app
from werkzeug.exceptions import HTTPException
from .error_definitions import ErrorCode, ERROR_MESSAGES
def register_error_handlers(app):
@app.errorhandler(APIError)
def handle_api_error(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.errorhandler(HTTPException)
def handle_http_error(error):
response = jsonify({
'message': error.description,
'status': error.code,
'error_code': f"E{error.code}"
})
response.status_code = error.code
return response
@app.errorhandler(Exception)
def handle_generic_error(error):
current_app.logger.error(f'Unhandled error: {str(error)}')
response = jsonify({
'message': ERROR_MESSAGES[ErrorCode.INTERNAL_ERROR.value],
'status': 500,
'error_code': ErrorCode.INTERNAL_ERROR.value
})
response.status_code = 500
return response