Throw client side errors from failed server-side requests in production
Answered
Pacific anchoveta posted this in #help-forum
Pacific anchovetaOP
I've written an axios interceptor to throw errors when one appears and I display this error in a toast notification using react-query.
My interceptor looks like this:
A standard hook looks like this;
When I get an error from a call, this works as expected on dev but when I push it to prod I get a generic NextJs error instead of the error I want to display:
My interceptor looks like this:
export const instance = axios.create({
baseURL: process.env.API_ENDPOINT,
headers: {
Authorization: `Basic ${process.env.API_SECRET}`,
},
validateStatus: (status) => status >= 200 && status <= 504,
});
instance.interceptors.response.use((response) => {
if (response.data.error) {
const { message } = response.data.error as ApiError<string>;
if (message !== 'Store order not found') {
throw new Error(message);
}
}
return response;
});A standard hook looks like this;
const useRequestPassword = () => {
return useMutation((email: string) => requestPassword(email), {
onError: (err: any) => {
getToast(err.message, 'error').fire();
},
});
};When I get an error from a call, this works as expected on dev but when I push it to prod I get a generic NextJs error instead of the error I want to display:
An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error. How can I resolve this?4 Replies
@joulev https://joulev.dev/blogs/throwing-expected-errors-in-react-server-actions
Pacific anchovetaOP
Thanks. I don't quite get how I can implement this in my case tho. Any tips?
@Pacific anchoveta Thanks. I don't quite get how I can implement this in my case tho. Any tips?
Instead of throwing an error, return an object indicating an error instead.
On the client, check if the received object is an error object and treat it as an error and show messages accordingly.
On the client, check if the received object is an error object and treat it as an error and show messages accordingly.