Best way to handle error logging in a server component
Unanswered
Billy posted this in #help-forum
BillyOP
Hi there,
In my SaaS-application, I've written a simple fetcher function, which handle the calls to my two main API endpoints. This is to make it easier to use across components and to make sure to utilize the Next.js fetch functionality.
I would love to somehow be able to log out the exact errors for staff-users, so they can see exactly what's going on, without having to do it every place where I use the component.
Do you have any ideas the best way to achieve this? Sending them to the client from this component.
I'm also considering making a new API endpoint to post errors to a global error log for all users, so I can keep track of all errors that occur in fetch calls.
In my SaaS-application, I've written a simple fetcher function, which handle the calls to my two main API endpoints. This is to make it easier to use across components and to make sure to utilize the Next.js fetch functionality.
I would love to somehow be able to log out the exact errors for staff-users, so they can see exactly what's going on, without having to do it every place where I use the component.
Do you have any ideas the best way to achieve this? Sending them to the client from this component.
I'm also considering making a new API endpoint to post errors to a global error log for all users, so I can keep track of all errors that occur in fetch calls.
3 Replies
@Billy I ran into a similar problem once. You cannot "Throw error" to client from server as it is masked by nextjs.
Best fix according to me was to use a try catch in server, and from catch return the error normally like a response.
On client side check the status code and handle error status codes as errors there.
Hope this helps.
Best fix according to me was to use a try catch in server, and from catch return the error normally like a response.
On client side check the status code and handle error status codes as errors there.
Hope this helps.
BillyOP
@JJSenpai Thank you for the quick reply and idea!
How did you achieve this, did you write the logic every place the function was called or did you handle it globally?
How did you achieve this, did you write the logic every place the function was called or did you handle it globally?
@Billy I only used it at one place so I hardcoded it. Something else you can do is create a wrapper fetch funtion which will handle it and use it everywhere.