What is the right way to throw an error message in NextJS 13.4 API? (Response, NextAPIResponse, NextResponse)
Asked Answered
B

1

6

Previously, throwing errors in the apis looked like this.

 if (error) {
      return response
      .status(500)
      .json({ error: 'Error getting data from Supabase' });

where the response was a NextAPIResponse object type. This no longer works, what is the right way to do it now? (Assuming that you are using app routing and not page routing.

Banjermasin answered 20/10, 2023 at 20:25 Comment(0)
B
7

While I'm sure there are many ways to do it, the way that I'm following is the way that is documented in the NextJS docs here.

In Typescript for clarity:

import { NextResponse } from 'next/server'
 
export async function GET(request: Request) {
  return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}

and Javascript for those that prefer it:

import { NextResponse } from 'next/server'
 
export async function GET(request) {
  return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
}

Note: I have experimented with replacing the word error in { error: 'Internal Server Error' } with {statusText: 'Internal Server Error' } since this is the default spec in the Web API; also, when you console log the received object from your fetch in NextJS (ie. when you console log that which is returned from your API) that key error turns to statusText. Either way has worked fine.

Banjermasin answered 20/10, 2023 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.