OutisO
tRPC3y ago
15 replies
Outis

Handling errors on the front-end

I'm making a mutation from my front-end and I intentionally throw a new TRPCError on my backend, I can see the trpc error on both client and server console but I don't understand how to catch it in the front-end

The mutation onError does nothing, myMutation.isError is false, myMutation.error is null and status "idle"

Here's some example code
const sendMessage = api.chatgpt.sendMessage.useMutation({
    onError: (error) => {
      console.log("error hit", error); //Doesn't execute
      setLoadingResponse(false);
    },
  });


And then on my code
sendMessage.mutate({ message: inputRef.current.value, chatId });


How I throw the error
if (result.status === 200) { //Yes 200 is on purpose so I can test it
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: "OpenAI API Error",
        });
      }


I also tried this
try {
      sendMessage.mutate({ message: inputRef.current.value, chatId });
    } catch (cause) {
      if (isTRPCClientError(cause)) {
        // `cause` is now typed as your router's `TRPCClientError`
        // Nothing gets printed
        console.log('data', cause.data);
                                   
      } 
    }


Pretty sure I'm just missing something here so a little help would be appreciated, thank you!
Was this page helpful?