如何在Koa.js中返回自定义JSON格式错误信息?
How to Return Custom JSON Error Responses in Koa
Hey there! Let's get that custom JSON error response working in your Koa invoiceHistory async method—since you're familiar with how it works in Laravel, the translation is pretty straightforward once you know Koa's context-based response system.
Here's a direct implementation matching your Laravel logic, adapted for Koa:
async invoiceHistory(ctx) { // Replace this with your actual async query logic (e.g., database call) const queryResult = await yourAsyncQueryFunction(); // Check if the query returned an error status if (queryResult.status === false) { // Set an appropriate HTTP status code (adjust based on your use case) ctx.status = 400; // Send your custom error JSON ctx.body = { status: 'error', message: 'your data is false' }; return; // Exit early so we don't run the success response code } // If everything checks out, send the success response with query results ctx.status = 200; // Optional—200 is Koa's default for successful responses ctx.body = { status: 'success', message: queryResult }; }
Key Notes for Koa:
- Context (
ctx) is your friend: Koa uses thectxobject to handle both incoming requests and outgoing responses.ctx.bodysets your response content, andctx.statuslets you define the HTTP status code (critical for proper API semantics). - Async/await is mandatory: Since
invoiceHistoryis an async method, make sure your query logic is asynchronous (useawaiton any promise-based operations like database calls). - Early returns prevent bugs: When you hit an error condition, use
returnto exit the method immediately—this stops the success response code from running accidentally.
Bonus: Handling Unexpected Errors
In real-world apps, you'll want to catch unexpected issues (like database failures) with a try/catch block. Here's an expanded version that includes that:
async invoiceHistory(ctx) { try { // Example: Fetch invoice history from a database const invoices = await InvoiceModel.find({ userId: ctx.request.params.userId }); // Custom error condition: No invoices found if (!invoices.length) { ctx.status = 404; ctx.body = { status: 'error', message: 'No invoice history found for this user' }; return; } // Success response (using 'data' instead of 'message' for clarity) ctx.body = { status: 'success', data: invoices }; } catch (err) { // Handle unexpected errors (e.g., connection issues, invalid queries) ctx.status = 500; ctx.body = { status: 'error', message: 'Failed to retrieve invoice history' }; console.error(err); // Log the error for debugging purposes } }
This way, you cover both intentional error conditions (like no data found) and unexpected failures (like database errors), making your API more robust.
内容的提问来源于stack exchange,提问作者Nasihun Amin Suhardiyan
相关产品推荐
相关产品推荐

