瀏覽代碼

导入ErrorSchema
为400/404错误添加application/json格式响应
统一错误响应格式

yourname 6 月之前
父節點
當前提交
ff15d756ee
共有 2 個文件被更改,包括 32 次插入11 次删除
  1. 26 6
      src/server/api/user.ts
  2. 6 5
      src/server/middleware/errorHandler.ts

+ 26 - 6
src/server/api/user.ts

@@ -2,6 +2,7 @@ import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
 import { UserService } from '../modules/users/user.service';
 import { z } from 'zod';
 import { AuthContext , authMiddleware } from '../middleware/auth.middleware';
+import { ErrorSchema } from '../middleware/errorHandler';
 
 const app = new OpenAPIHono<AuthContext>()
 const userService = new UserService();
@@ -44,7 +45,14 @@ const createUserRoute = createRoute({
         }
       }
     },
-    400: { description: 'Invalid input' }
+    400: {
+      content: {
+        'application/json': {
+          schema: ErrorSchema
+        }
+      },
+      description: 'Invalid input'
+    }
   }
 });
 
@@ -83,7 +91,7 @@ const listUsersHandler = app.openapi(
       };
     })
   
-    return c.json(usersOut);
+    return c.json(usersOut, 200);
   }
 );
 
@@ -106,7 +114,14 @@ const getUserRoute = createRoute({
         }
       }
     },
-    404: { description: 'User not found' }
+    404: {
+      content: {
+        'application/json': {
+          schema: ErrorSchema
+        }
+      },
+      description: 'User not found'
+    }
   }
 });
 
@@ -115,8 +130,13 @@ const getUserHandler = app.openapi(
   async (c) => {
     const { id } = c.req.valid('param');
     const user = await userService.getUserById(parseInt(id));
-    if (!user) return c.notFound();
-    return c.json(user);
+    if (!user) return c.json({ code: 404, message: 'User not found' }, 404);
+    return c.json({
+      id: user.id,
+      username: user.username,
+      email: user.email,
+      createdAt: user.createdAt.toISOString()
+    }, 200);
   }
 );
 
@@ -157,7 +177,7 @@ const updateUserHandler = app.openapi(
     const data = c.req.valid('json');
     const user = await userService.updateUser(parseInt(id), data);
     if (!user) return c.notFound();
-    return c.json(user);
+    return c.json(user, 200);
   }
 );
 

+ 6 - 5
src/server/middleware/errorHandler.ts

@@ -13,11 +13,12 @@ export const ErrorSchema = z.object({
 
 export const errorHandler = async (err: Error, c: Context) => {
   if (err instanceof HTTPException) {
+    const details = err.cause ? { details: err.cause instanceof Error ? err.cause.message : err.cause } : {} 
     return c.json(
       { 
-        error: err.message,
-        status: err.status ,
-        cause: err.cause instanceof Error ? err.cause.message : err.cause
+        code: err.status,
+        message: err.message,
+        ...details
       },
       err.status
     )
@@ -25,8 +26,8 @@ export const errorHandler = async (err: Error, c: Context) => {
 
   return c.json(
     { 
-      error: err.message || 'Internal Server Error',
-      status: 500 
+      code: 500,
+      message: err.message || 'Internal Server Error'
     },
     500
   )