Query 에러 처리
retry - 옵션을 통해 여러번 호출하더라도 에러 처리는 한번만 실행한다.
global error
- new QueryCache 로 인스턴스를 생성후 내부에 에러 처리를 설정한다.
- 내부 쿼리에 onError 설정을 하더라도 에러를 처리한다.
const queryClient = new QueryClient({
queryCache: new QueryCache({
onError: (error) => {
console.log("global error");
},
}),
});
default error
- 모든 쿼리에 대해 기본 에러를 설정한다.
- 만약 다른 쿼리 내부에 onError 처리 설정시 default error 는 동작하지 않는다.
const queryClient = new QueryClient({
defaultOptions: {
queries: {
onError: (error: unknown | AxiosError) => {
console.log("default error");
},
},
},
});
local error
- 각 쿼리에 지역적으로 에러 처리를 생성한다.
const useTestQuery = () => {
const fetch = () => client.get("/test").then((res) => res.data);
const query = useQuery("test", fetch, {
onSuccess(data) {},
onError(err) {
console.log("local error");
},
});
return query;
};
에러 전파 순서
global error → local error || default error
mutation 에러처리
global error
const queryClient = new QueryClient({
mutationCache: new MutationCache({
onError: (error) => {
// any error handling code...
console.error("global error");
},
}),
})
default error
const queryClient = new QueryClient({
defaultOptions: {
mutations: {
onError(error, variables, context) {
console.log("default error");
},
},
},
});
local error
const queryClient = new QueryClient({
defaultOptions: {
mutations: {
onError(error, variables, context) {
console.log("default error");
},
},
},
});
try-catch error
onClick={async () => {
try {
const result = await testMutation.mutateAsync();
} catch (e) {
console.log("try-catch-error");
}
}}
에러 전파 순서
global error → local error || default error → try-catch error
- 전역, UI 적 공통 처리를 위한 에러 처리는 global 에, 데이터 처리는 로컬에, 내부 알림 같은 지역적 UI 에러 처리는 try-catch 영역에 사용하는 것이 좋다.
Reference
React Query Error Handling
After covering the sunshine cases of data fetching, it's time to look at situations where things don't go as planned and "Something went wrong..."
tkdodo.eu
There might be incorrect information or outdated content.
'Web > React' 카테고리의 다른 글
[REACT] React 기본 Hooks (0) | 2023.08.24 |
---|---|
[REACT] react router “/” handling (0) | 2023.08.03 |
[REACT] react-query (v3) (0) | 2023.08.02 |
[REACT] Unexpected token '<' issue 🔥 (0) | 2023.07.29 |
[REACT] CRA version up issue 🔥 (0) | 2023.07.29 |