Set different unsuccessful status codes on page (RSC) when fetching or something else goes wrong? #50383
Replies: 4 comments 4 replies
-
Using the Example:
For more information, check out this docs. Another option I would suggest is to handle errors using
For more information, check out this docs. |
Beta Was this translation helpful? Give feedback.
-
Would be happy if something like a Example:
|
Beta Was this translation helpful? Give feedback.
-
You mentioned server component but it looks like you are talking about api routes using the app folder. If so, this works for me if I put this file in the folder import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
export async function POST(request: Request) {
const res = await request.json();
const { newsSourceFromId, newsSourceToId, promptsId, response } = res;
if (!newsSourceFromId || !newsSourceToId || !promptsId || !response) {
return NextResponse.json(
{ error: "Missing required fields" },
{ status: 400 }
);
}
try {
const newChatResponse = await prisma.chatResponses.create({
data: {
newsSourceFromId: 120,
newsSourceToId,
promptsId: promptsId,
response,
creationDate: new Date(), // current datetime in GMT
},
});
return NextResponse.json({
message: "Successful Insertion id:" + newChatResponse.id,
});
} catch (error) {
const err = error as Error;
return NextResponse.json({ error: err.message }, { status: 500 });
}
} |
Beta Was this translation helpful? Give feedback.
-
@ludwighogstrom @danieljee @HamAndRock |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a way to set different status codes when an error occurs in a server component?
For example, I would like to distinguish when an error originates from an external api call (status code
502
) or if something is wrong with the application itself (status code500
) when monitoring the site.Tried to find information about it in the documentation but only found that you can throw or use
notFound()
fromimport { notFound } from 'next/navigation'
.Beta Was this translation helpful? Give feedback.
All reactions