Exception Handling
Exception Handling
The framework has a built-in unified exception handler. Throw a business exception and the framework formats the response for you.
Core features
- Unified capture: the framework catches and formats every exception response
- Rich exception types: built-in classes for common business cases
- Internationalization: exception messages can be localized
- Detailed errors: custom messages and error codes
- Extensible: define your own exception types for special cases
Overview
| Feature | Description | Benefit |
|---|---|---|
| Unified exception handling | The framework catches and formats exceptions | Removes error-handling boilerplate and keeps responses consistent |
| Built-in exception types | Common exception classes | Faster development, less repeated code |
| Custom exceptions | Extend the base classes | Handles special business cases |
| i18n integration | Multilingual exception messages | Better experience for global apps |
| Error code management | Custom error codes | Easier client-side handling and debugging |
Quick Start
Raising Exceptions
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.exceptions import RPCException, ValidationError, UnauthorizedError
app = ServerApplication("app.socket")
@app.route(name="hello")
async def hello(name: str = None):
"""Greeting endpoint example"""
if not name:
raise ValidationError("姓名参数不能为空")
if name == "admin":
raise UnauthorizedError("管理员账户禁止访问")
return {"message": f"Hello, {name}!"}
if __name__ == "__main__":
asyncio.run(app.run())Sample Response
When an exception is raised, the framework formats a unified error response automatically:
{
"jsonrpc": "2.0",
"result": {
"code": 400,
"meta": {"endpoint": null, "close": 1},
"data": null,
"msg": "姓名参数不能为空"
},
"id": 1
}Built-in Exception Types
The framework ships with exception classes for common business cases. All of them inherit from RPCException.
Important
Every exception class inherits from RPCException, which keeps exception handling consistent.
Exception Reference
| Exception | Description | When to use | Example |
|---|---|---|---|
RPCException | Base exception | Generic business errors | raise RPCException("操作失败") |
UnauthorizedError | Access to an unauthorized resource | Authentication or permission failure | raise UnauthorizedError("用户未登录") |
ValidationError | Parameter validation failure | Wrong format or missing required parameter | raise ValidationError("邮箱格式不正确") |
FileNotFoundError | Resource not found | The requested resource does not exist | raise FileNotFoundError("用户不存在") |
ValueError | Invalid parameter value | Out-of-range value or type mismatch | raise ValueError("年龄必须在0-150之间") |
RuntimeError | Runtime error | Internal failure or third-party service error | raise RuntimeError("数据库连接失败") |
AttributeError | Object attribute error | Accessing a missing attribute | raise AttributeError("对象缺少必要属性") |
Info
Every exception returned by the framework uses the 400 status code.
Internationalization
Exception messages support i18n and can be returned in the client's language.
Additional Notes
Recommendations
- Pick the right type: choose the exception class that matches the failure.
- Be specific: include enough context to debug and to help the user.
- Manage error codes: define a consistent set of codes for different failures.
- Localize: provide multilingual messages for global apps.
- Test exceptions: make sure the handling logic is correct.
Custom Error Codes and Data
RPCException accepts custom error codes and extra data:
# Custom code and message
raise RPCException(code=410, msg="用户不存在")
# Exception with extra data
raise RPCException(
code=410,
msg="用户不存在",
data={"user_id": 123, "suggestion": "请检查用户ID是否正确"}
)
# Business example
@app.route(name="get_user_profile")
async def get_user_profile(user_id: int):
user = await find_user(user_id)
if not user:
raise RPCException(
code=404,
msg="用户资料不存在",
data={
"user_id": user_id,
"timestamp": datetime.now().isoformat(),
"suggestion": "请确认用户ID是否正确"
}
)
return {"profile": user.to_dict()}Sample response:
{
"jsonrpc": "2.0",
"result": {
"code": 404,
"meta": {"endpoint": "get_user_profile", "close": 1},
"data": {
"user_id": 123,
"timestamp": "2024-01-15T10:30:00",
"suggestion": "请确认用户ID是否正确"
},
"msg": "用户资料不存在"
},
"id": 1
}