tRPCttRPC
Powered by
OutisO
tRPC•3y 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);
    },
  });
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 });
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",
        });
      }
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);
                                   
      } 
    }
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!
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Catch TRPCError, ZoddError on the front-end
CaptainCCaptain / ❓-help
4y ago
Dynamic input not leading to changes on the front end
MiNiMALMMiNiMAL / ❓-help
3y ago
handling errors server side
agiAagi / ❓-help
3y ago