Apollo client not paring UserInputError - reactjs

i am throwing an UserInputError from the Apollo server, the playground is correctly displaying the error with extension and exceptions, but the the apollo client is not showing the extensions and exceptions.

Stringify the error and found that ,we can access it using error.graphQlErrors[0] , it's weird that it's not written anywhere in the documentation. This sure gave me a lot of trouble

The existing answer worked for me. Just providing some more details to help future Googlers.
On the apollo-server backend, we are throwing an error:
throw new UserInputError("Form Arguments invalid", {
field: "name",
});
On the apollo-client frontend, we are catching that error:
try {
// Perform GraphQL mutation.
} catch (error) {
// How do we get the "field" extra info?
}
As the previous answer says, there is some graphQlErrors property that contains extra information. So in this example, I can access error.graphQlErrors[0].extensions.field to get the "name" value.

Related

Getting unwrapped value by default

I am currently working on a project that requires using rtk query. Is there a way to get unwrapped value by default for mutations.
const [removeStudent] = useRemoveStudentMutation()
and i have the call for removeStudent() within try catch because removeStudent can fail in which case i show an error message. Something like this.
try{
await removeStudent().unwrap()
// logic for showing success message
}
catch(e){
//logic for showing error message
}
problem is if i don't use unwarp i'm getting a success message even when the removeStudent() failed. Is there a way i could make unwrap() apply to all mutations.So that i don't have to use unwrap every time i write a mutation.Maybe at createApi level
Thanks

What's the type of React Query's Error and how to handle different cases?

I'm using React Query with typescript to fetch data in my project and I'm trying to use the error the useQuery hook returns to display a message describing the error if it exists like this :
{isError && (error)? <p className=" text-[#ff0000] text-center font-semibold">{error?.response.data.message}</p> : null}
I'm having a problem with the error type :
How can I fix it, I couldn't find anything on the internet and if possible can anyone explain how to handle different thrown error with react query since you can throw anything in JS/TS
error defaults to type unknown because your queryFn can throw anything, that's a javascript behaviour. throw 5 will give you number as your error type. There is no good way to assert that, so unknown is the best possible type. It's also what TypeScript does now per default since v4.4 (useUnknownInCatchVariables)
The best way to make sure that your app runs as you want is to narrow the type at runtime. if (error instanceof Error) does the trick, and the you can safely access error.message.
If you are using axios, the type is actually an AxiosError, and axios has an axios.isAxiosError(error) helper that checks for that and also narrows the type correctly.
The alternative is to provide generics to useQuery:
useQuery<Todo[], AxiosError>(['todos'], fetchTodos)
but this is bad for a couple of reasons:
there are actually four generics, and you remove a bunch of features by only providing two of them
There is no guarantee that your error will really be an axios error. For example, if you use select, and a runtime error happens in there (because of some faulty logic), your error will be a "normal" Error, but not an axios Error.
Alas, as you can throw anything in JS, unknown is the most correct type.
I'm also going into more details in my blog:
https://tkdodo.eu/blog/react-query-and-type-script
As #TkDodo has pointed out, you could provide generics to useQuery but it's not worth it, since you will lose the Type inference too.
However, as a workaround, I add the onError callback and type its error arg instead. TypeScript will infer the type of that error to the type I am expecting from useQuery.
Note that I am using Axios request & response interceptors for all requests that I use to format and throw my custom errors.
Example...
interface IPayload {
someKey: string; // ETC
}
// The type of error expected from the response (also formatted by interceptor).
interface IApiError {
message: string;
description: string;
statusCode: string | number;
}
export const useMyQuery = (payload: IPayload) => {
const { data, isLoading, isError, error, refetch } = useQuery({
queryKey: ['some', 'query-keys'],
queryFn: () => API.fetchMyData(payload),
// This does the trick
onError: (err: IApiError) => err,
});
};
I had same issue with Typescript and react-query, same error Object is of type 'unknown'.
Installing this devDependency "#types/react-query" helped me somehow. I am using VS Code editor and I think that helped with type suggestions. This might help.
npm i --save-dev #types/react-query
For Mutation only:
If you are using Axios for Api calls, use the following to get Axios type errors:
const error = mutation.error as AxiosError;
Now, the error object will not throw any object not found warning.

React Redux: How to handle errors in RTK Queries/Mutation Typescript?

Hope your all are doing fine.
Im using Typescript with RTK mutation everything is working good but if i send any error from backend in specific json format like
{
status: "Error",
message "Something went wrong"
}
when i check on my browser network tab its showing me the correct error response like:
{
data: {
status: "Error",
message "Something went wrong"
}
}
Im getting error in the mutation hook:
const [createCategory, {isLoading, error }] = useCreateCategoryMutation();
but I can't access error.data.message in my react it is giving me types error like:
Property 'data' does not exist on type 'FetchBaseQueryError | SerializedError'.
At this point, it could be an error from the server (FetchBaseQueryError) or just any error thrown by code you wrote (SerializedError, e.g. in query, queryFn, transformResponse etc.) - and that could have a completely different shape.
To make sure it's a FetchBaseQueryError, just do
if ('data' in error) {
// TypeScript will handle it as `FetchBaseQueryError` from now on.
}
I found the answer for your question here written by Phry as well :) ,
https://github.com/rtk-incubator/rtk-query/issues/86#issuecomment-738845312
If you know the format that will be returned with all non-2xx-status responses from your server, you could just cast your
fetchQuery as BaseQueryFn<string | FetchArgs, unknown, YourErrorType, {}>.

Chrome WebSpeech API returning not-allowed error?

I was using Web Speech API for speech to text. But when calling recognition.start() it is showing me SpeechRecognitionErrorEvent
recognition = new webkitSpeechRecognition()
recognition.continuous = false
recognition.interimResults = false
recognition.onend = () => console.log("ended")
recognition.onerror = () => console.log("errored")
recognition.start()
Its logging,
errored
ended
SpeechRecognitionErrorEvent {isTrusted: true, error: "not-allowed", message: "", type: "error", target: SpeechRecognition, …}
I tried it in my react project. Trying to trigger the recognizer from chrome console also results in the same error.
Someone else, as I am using it for the first time I cannot quite grasp the reason for this error. Another question with the same issue was raised in stackoverflow from where I couldn't got an clear answer. Is it that I must request the speech api start method with a ssl certificate. Otherwise, I cannot use the feature.
UPDATE:
I had to enable microphone permission manually in the browser to get rid of this error.
Just for the record, another reason this error can occur is if you are sending a Permissions-Policy header (W3C Working Draft) in your HTTP responses and include the string microphone=() to disable access to the microphone. This header is typically used to prevent malicious third-party scripts from asking for the microphone.
Try this :
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.start()

How do I show the user the specific http response code & message using React Hooks

I am using an API to get info & I would like to show user specific error message and code when there is an error. Specifically, with this project if I do too many requests too quick I get a 429: Too many requests.
I would like to show this to the user but when I console.log the error I am getting something different than the response code. I get Syntax error: < at 0 JSON position.
Please help! Thanks in advance.
What I'm really sure of is that your server returns some HTML layout in the response. And you try to parse it as JSON string via data.json() and of course, you get the syntax error since it's not JSON (HTML layout starts with < symbol hence the error: SyntaxError: Unexpected token <) - Same Error like yours.
You can get the status code and error message like below.
fetch(API).then((response) => {
console.log('status code', response.status)
})
.catch((error) => {
console.log('error msg', error.message)
})

Resources