Skip to main content
Version: 4.xx.xx
Source Code

useOnError

useOnError calls the onError method from the authProvider under the hood.

It returns the result of react-query's useMutation, which includes many properties like isSuccess and isError.

Data that is resolved from the onError will be returned as the data in the query result with the following type:

type OnErrorResponse = {
redirectTo?: string;
logout?: boolean;
error?: Error;
};

According to the onError method's returned values, the following process will be executed:

  • redirectTo: If it has a value, the app will be redirected to the given URL.
  • logout: If it is true, useOnError calls the logout method.
  • error: An Error object representing any errors that may have occurred during the operation.

Internal Usage​

Refine uses useOnError internally in the data hooks to handle errors in a unified way.

When an error is thrown by any data hook, the useOnError function is triggered with the error object. Afterward, the error object is passed to the onError method of the authProvider, which can be utilized to redirect the user or to log them out.

import type { AuthProvider } from "@refinedev/core";

const authProvider: AuthProvider = {
// ...
onError: (error) => {
const status = error.status;
if (status === 418) {
return {
logout: true,
redirectTo: "/login",
error: new Error(error),
};
}
return {};
},
// ---
};

For more information about data hooks, refer to the Data Provider documentation→

Usage​

Let's say that a payment request was declined by the API. If the error status code is 418, the user will be logged out for security reasons:

import { useOnError } from "@refinedev/core";

const { mutate: onError } = useOnError();

fetch("http://example.com/payment")
.then(() => console.log("Success"))
.catch((error) => onError(error));

We have a logic in authProvider's onError method like below.

import type { AuthProvider } from "@refinedev/core";

const authProvider: AuthProvider = {
onError: (error) => {
const status = error.status;
if (status === 418) {
return {
logout: true,
redirectTo: "/login",
error: new Error(error),
};
}
return {};
},
// ---
};