83 lines
2.8 KiB
YAML
83 lines
2.8 KiB
YAML
id: standard-error-response
|
|
name: 标准错误响应格式规则
|
|
description: 验证API错误响应是否符合标准格式
|
|
category: ErrorHandling
|
|
version: 1.0.0
|
|
severity: warning
|
|
is_enabled: true
|
|
tags:
|
|
- error-handling
|
|
- response-format
|
|
target_type: APIResponse
|
|
lifecycle: ResponseValidation
|
|
scope: ResponseBody
|
|
error_code: "*" # 匹配所有错误码
|
|
expected_status: -1 # 不验证状态码
|
|
code: |
|
|
def validate(context):
|
|
response = context.get('api_response')
|
|
if not response:
|
|
return {'is_valid': False, 'message': '缺少API响应对象'}
|
|
|
|
# 只检查4xx和5xx状态码的响应
|
|
if response.status_code < 400:
|
|
return {'is_valid': True, 'message': '非错误响应,跳过验证'}
|
|
|
|
# 确保响应包含JSON内容
|
|
if not response.json_content:
|
|
return {
|
|
'is_valid': False,
|
|
'message': '错误响应不是有效的JSON格式',
|
|
'details': {
|
|
'status_code': response.status_code,
|
|
'content_type': response.headers.get('Content-Type', '未知')
|
|
}
|
|
}
|
|
|
|
# 检查错误响应的必要字段
|
|
required_fields = ['code', 'message']
|
|
missing_fields = [field for field in required_fields if field not in response.json_content]
|
|
|
|
if missing_fields:
|
|
return {
|
|
'is_valid': False,
|
|
'message': '错误响应缺少必要字段',
|
|
'details': {
|
|
'missing_fields': missing_fields,
|
|
'required_fields': required_fields,
|
|
'response': response.json_content
|
|
}
|
|
}
|
|
|
|
# 检查字段类型
|
|
if not isinstance(response.json_content.get('code'), (str, int)):
|
|
return {
|
|
'is_valid': False,
|
|
'message': '错误码字段类型不正确',
|
|
'details': {
|
|
'field': 'code',
|
|
'expected_type': 'string或integer',
|
|
'actual_type': type(response.json_content.get('code')).__name__
|
|
}
|
|
}
|
|
|
|
if not isinstance(response.json_content.get('message'), str):
|
|
return {
|
|
'is_valid': False,
|
|
'message': '错误消息字段类型不正确',
|
|
'details': {
|
|
'field': 'message',
|
|
'expected_type': 'string',
|
|
'actual_type': type(response.json_content.get('message')).__name__
|
|
}
|
|
}
|
|
|
|
return {
|
|
'is_valid': True,
|
|
'message': '错误响应符合标准格式',
|
|
'details': {
|
|
'status_code': response.status_code,
|
|
'error_code': response.json_content.get('code'),
|
|
'error_message': response.json_content.get('message')
|
|
}
|
|
} |