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

NextJS 13.4 app routing API中正确抛出错误消息的方法

App Router下Next.js API路由返回错误的正确写法

之前在Page Router中使用NextAPIResponse返回错误的写法已经不适用于App Router,以下是正确的实现方式:

核心区别

App Router的API路由不再依赖NextAPIResponse对象,而是通过NextResponse类构建响应——无需传入res参数,直接在路由函数中返回NextResponse实例即可。

代码示例

import { NextResponse } from 'next/server';

// 以GET请求为例
export async function GET() {
  try {
    // 执行Supabase数据获取逻辑
    const { data, error } = await supabase.from('your_table').select('*');
    
    if (error) throw error;
    
    return NextResponse.json(data);
  } catch (error) {
    // 返回500错误及对应信息
    return NextResponse.json(
      { error: 'Error getting data from Supabase' },
      { status: 500 }
    );
  }
}

关键点说明

  • 导入NextResponse:从next/server中引入该类,这是App Router处理响应的核心工具
  • 响应构建:调用NextResponse.json()方法,第一个参数是响应体内容,第二个参数是配置对象,可指定status状态码
  • 错误处理:在try/catch块中捕获异常,直接返回对应状态码的错误响应即可

其他错误场景示例

比如返回400参数错误:

return NextResponse.json(
  { error: 'Invalid request parameters' },
  { status: 400 }
);

内容的提问来源于stack exchange,提问作者Octo Palm Tree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:12:39