Error handling react + next routes api
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
Hello, i dont remember what returns error in javascript, what is the good way to handle errors. in this example:
8 Replies
Sun bearOP
export async function GET() {
try {
const messages = await getMessages();
return NextResponse.json({ messages });
} catch (e) {
// TODO: good way to handle this error, not like status === 500
return NextResponse.json({
status: 500,
body: "Could not fetch messages",
});
}
}export async function fetchMessages() {
const response = await fetch("/api/messages");
const data = await response.json();
if (data.status === 500) {
throw new Error(data.body);
}
return data.messages as Message[];
}and finally in react
const setInitialMessages = async () => {
try {
const messages = await fetchMessages();
setMessages(messages);
} catch (error: any) {
setError({
message: error.message,
});
} finally {
setLoading(false);
}
};i want to handle errors in last code
on react js side
but i dont know which ones should i check or anything else
how function stack works with errors