🚨 エラーハンドリング
堅牢なバックエンドサービスを構築するには適切なエラーハンドリングが不可欠です。NodeBlocks SDKは、すべてのサービスで一貫したユーザーフレンドリーなエラーレスポンスを確保するための包括的なエラーハンドリングパターンを提供します。
🎯 エラーレスポンス形式
すべてのNodeBlocksサービスは、一貫したJSON形式でエラーを返します:
{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}
検証エラー
リクエスト検証が失敗した場合、追加の詳細が含まれます:
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'name'",
"request body must have required property 'email'",
"request body must NOT have additional properties"
]
}
}
📋 一般的なエラーコード
400 Bad Request
- Validation Error - リクエストボディの形式が無効または必須フィールドが欠落
- Failed to create [entity] - データベース挿入操作が挿入IDを返せなかった
- Failed to update [entity] - 更新操作でデータが変更されなかった(変更が検出されなかった)
- Failed to delete [entity] - データベース削除操作が失敗した
401 Unauthorized
- token could not be verified - 認可トークンが欠落または無効
- Authentication failed - 認証トークンが欠落または無効
- Token fails security check - トークンのセキュリティ検証が失敗した
403 Forbidden
- User is not authorized to access this resource - ユーザーに必要な権限がない
- User is not authorized to access this [entity] - ユーザーに特定のエンティティ権限がない
404 Not Found
- [Entity] not found - リクエストされた操作に対してエンティティが存在しない
- [Entity] does not exist - リクエストされた操作に対してエンティティが存在しない
409 Conflict
- [Entity] already exists - 同じ識別子を持つエンティティが既に存在する
- User with this email already exists - このメールアドレスのユーザーが既に存在する
500 Internal Server Error
- Failed to create [entity] - 作成中のデータベース接続問題または予期しない失敗
- Failed to get [entity] - 取得中のデータベース接続問題または予期しない失敗
- Failed to find [entities] - リスト中のデータベース接続問題、無効なフィルター構文、または予期しない失敗
- Failed to update [entity] - 更新中のデータベース接続問題または予期しない失敗
- Failed to delete [entity] - 削除中のデータベース接続問題または予期しない失敗
🔧 サービス固有のエラーパターン
認証サービスエラー
{
"error": {
"message": "token could not be verified"
}
}
{
"error": {
"message": "Authentication failed"
}
}
ユーザーサービスエラー
{
"error": {
"message": "User profile not found"
}
}
{
"error": {
"message": "Identity is not authorized to access this resource"
}
}
組織サービスエラー
{
"error": {
"message": "Organization not found"
}
}
{
"error": {
"message": "Failed to create organization"
}
}
プロダクトサービスエラー
{
"error": {
"message": "Product not found"
}
}
{
"error": {
"message": "Failed to create product"
}
}
カテゴリサービスエラー
{
"error": {
"message": "Category does not exist"
}
}
{
"error": {
"message": "Failed to create category"
}
}
属性サービスエラー
{
"error": {
"message": "Attribute group not found"
}
}
{
"error": {
"message": "Failed to create attribute group"
}
}
オーダーサービスエラー
{
"error": {
"message": "Order not found"
}
}
{
"error": {
"message": "Failed to create order"
}
}
チャットサービスエラー
{
"error": {
"message": "Channel not found"
}
}
{
"error": {
"message": "Chat message not found"
}
}
📐️ エラーハンドリングのベストプラクティス
1. 一貫したエラーメッセージ
すべてのサービスで一貫したユーザーフレンドリーなエラーメッセージを使用します:
// ✅ 良い例: 明確で実行可能なエラーメッセージ
"User profile not found"
"Failed to create organization"
"Validation Error"
// ❌ 避けるべき: 技術的または不明瞭なメッセージ
"Database connection failed"
"Internal server error"
"Something went wrong"
2. 適切なHTTPステータスコード
異なるエラータイプに対して適切なHTTPステータスコードを使用します:
- 400 - Bad Request(検証エラー、欠落フィールド)
- 401 - Unauthorized(認証失敗)
- 403 - Forbidden(認可失敗)
- 404 - Not Found(エンティティが存在しない)
- 409 - Conflict(重複エンティティ)
- 500 - Internal Server Error(データベース問題、予期しない失敗)
3. 検証エラーの詳細
data
配列に具体的な検証エラーの詳細を含めます:
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'name'",
"request body must have required property 'email'",
"request body must NOT have additional properties"
]
}
}
4. 認証エラーハンドリング
常に認証エラーを最初にチェックします:
// 処理前に認証を確認
if (!isAuthenticated(request)) {
return {
status: 401,
body: {
error: {
message: "token could not be verified"
}
}
};
}
5. 認可エラーハンドリング
保護された操作に対してユーザーの権限をチェックします:
// 管理者専用操作の認可を確認
if (!hasAdminRole(user)) {
return {
status: 403,
body: {
error: {
message: "User is not authorized to access this resource"
}
}
};
}
⚙️ エラーミドルウェアの設定
アプリケーション全体で一貫したエラーハンドリングを確保するために、nodeBlocksErrorMiddleware
を使用します:
import express from 'express';
import { MongoClient } from 'mongodb';
import { middlewares, services } from '@nodeblocks/backend-sdk';
const { nodeBlocksErrorMiddleware } = middlewares;
const { userService, organizationService } = services;
const client = new MongoClient('mongodb://localhost:27017').db('dev');
express()
.use(userService({
users: client.collection('users'),
identity: client.collection('identity')
}))
.use(organizationService({
organizations: client.collection('organizations'),
identity: client.collection('identity')
}))
.use(nodeBlocksErrorMiddleware()) // 最後に配置する必要がある
.listen(8089, () => console.log('Server running'));
⚠️ 重要: すべてのエラーが適切にJSONレスポンスとしてフォーマットされるように、ルートとサービスの後に
nodeBlocksErrorMiddleware()
を常に追加してください。
🔍 エラーデバッグ
開発モード
開発モードでは、追加のエラーの詳細が含まれる場合があります:
{
"error": {
"message": "Database connection failed",
"stack": "Error: Database connection failed\n at createUser...",
"data": {
"operation": "createUser",
"timestamp": "2024-05-28T09:41:22.552Z"
}
}
}
プロダクションモード
プロダクションでは、必要なエラー情報のみが返されます:
{
"error": {
"message": "Internal server error"
}
}
📝 エラーロギング
構造化ロギング
より良いデバッグのために構造化データでエラーをログ記録します:
const logError = (error: any, context: any) => {
console.error('API Error:', {
message: error.message,
status: error.status,
timestamp: new Date().toISOString(),
endpoint: context.endpoint,
userId: context.userId,
requestId: context.requestId
});
};
エラーモニタリング
エラーモニタリングサービスとの統合を検討してください:
// エラーモニタリングサービスを使用した例
const handleError = (error: any, req: any, res: any) => {
// モニタリングサービスにログ記録
errorMonitoringService.captureException(error, {
extra: {
endpoint: req.path,
method: req.method,
userId: req.user?.id
}
});
// ユーザーフレンドリーなレスポンスを返す
res.status(error.status || 500).json({
error: {
message: error.message || 'Internal server error'
}
});
};