You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 the ctx object to handle both incoming requests and outgoing responses. ctx.body sets your response content, and ctx.status lets you define the HTTP status code (critical for proper API semantics).
  • Async/await is mandatory: Since invoiceHistory is an async method, make sure your query logic is asynchronous (use await on any promise-based operations like database calls).
  • Early returns prevent bugs: When you hit an error condition, use return to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:49:21