Error handling in app router
Unanswered
Common paper wasp posted this in #help-forum
Common paper waspOP
Let say I have a function that handles getting data, this function will be used in server action and also in server side fetching in a page:
Now this is how I use it in a page:
And in server action:
And then in a client component i use this server action like this:
I'll be honest I have no clue what I'm doing with all those errors. Is there a smooth way to handle errors?
export async function getLatestPrices(): Promise<BonbastLatest | undefined> {
try {
const token = await getToken();
if (!token) {
throw new Error(`Token not available`);
}
const myData = "mydatathatgoestoserver"
const response = await fetch(`${BASE_URL}/json`, {
method: "POST",
body: myData,
});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
Now this is how I use it in a page:
export default async function Home() {
const data = await getLatestPrices();
if (!data) {
throw new Error("Could not load prices");
}
return (
<div>
<ShowData initialData={data} />
</div>
);
}
And in server action:
"use server";
import { getLatestPrices } from "@/lib/api";
export async function updateLatestsPrices() {
try {
const data = await getLatestPrices();
return data;
} catch (err) {
console.error(err);
throw new Error("Failed to get latest prices");
}
}
And then in a client component i use this server action like this:
export default function ShowData({ initialData }: Props) {
const [data, setData] = useState(initialData);
useEffect(() => {
const interval = setInterval(async () => {
const data = await updateLatestsPrices();
if (!data) return;
setData(data);
}, 45000);
return () => clearInterval(interval);
}, []);
return (
<div>
<h3>Data</h3>
<pre
>
{JSON.stringify(data, null, 2)}
</pre>
</div>
);
}
I'll be honest I have no clue what I'm doing with all those errors. Is there a smooth way to handle errors?
3 Replies
Common paper waspOP
Bump 😦
you could log it somewhere, maybe in a db and go through errors one by one.
in a page.tsx