like-gold
like-gold7mo ago

Showing error message from server on HTTP error

Hello, I'm a backender and playing with Refine so I'm new to React. I have an "create new item" page and copied to code from the inferencer. When the request to server failed I see a red notification with an HTTP 500 error. The response from the server contains information what was wrong. How can I present this to the user? I tried to add a errorNotification to useForm, but that doesn't seem to work. Any help or pointer is welcome.
3 Replies
kapa.ai
kapa.ai7mo ago
Hi @MajorD. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Refine provides out-of-the-box support for server-side validation and error handling. To display server-generated validation errors, you need to ensure that your server returns errors in a specific format that Refine can understand. This format is defined by the HttpError interface:
type HttpError = {
statusCode: number;
message: string;
errors: {
[field: string]: string | string[] | boolean | { key: string; message: string };
};
};
type HttpError = {
statusCode: number;
message: string;
errors: {
[field: string]: string | string[] | boolean | { key: string; message: string };
};
};
In this structure, the errors field is used for server-side validation. When the errors field is set, Refine's useForm will automatically display the error messages in the form with the corresponding fields. Here is an example of how to implement error handling in your data provider:
import { DataProvider, HttpError } from "@refinedev/core";

export const dataProvider = (apiUrl: string): DataProvider => ({
getOne: async ({ resource, id }) => {
try {
const response = await fetch(`<https://api.example.com/${resource}/${id}`>);

if (!response.ok) {
const error: HttpError = {
message: response.statusText,
statusCode: response.status,
};
return Promise.reject(error);
}

return {
data: response.data,
};
} catch (error) {
const error: HttpError = {
message: error?.message || "Something went wrong",
statusCode: error?.status || 500,
};
return Promise.reject(error);
}
},
// ...
});
import { DataProvider, HttpError } from "@refinedev/core";

export const dataProvider = (apiUrl: string): DataProvider => ({
getOne: async ({ resource, id }) => {
try {
const response = await fetch(`<https://api.example.com/${resource}/${id}`>);

if (!response.ok) {
const error: HttpError = {
message: response.statusText,
statusCode: response.status,
};
return Promise.reject(error);
}

return {
data: response.data,
};
} catch (error) {
const error: HttpError = {
message: error?.message || "Something went wrong",
statusCode: error?.status || 500,
};
return Promise.reject(error);
}
},
// ...
});
In your form, you can then use the useForm hook to handle the error and display the error message:
const {
mutationResult: { error },
formLoading,
onFinish,
} = useForm();
const { errors } = error ?? {};

// In your form fields
<span style={{ color: "red" }}>{errors?.name ?? ""}</span>
const {
mutationResult: { error },
formLoading,
onFinish,
} = useForm();
const { errors } = error ?? {};

// In your form fields
<span style={{ color: "red" }}>{errors?.name ?? ""}</span>
For more information, you can refer to the Server Side Validation (https://refine.dev/docs/advanced-tutorials/forms/server-side-form-validation/) documentation and the Error Format (https://refine.dev/docs/data/data-provider#error-format) section in the Data Provider documentation. Regarding the errorNotification prop in useForm, it seems there might be some confusion. The errorNotification prop is actually used in the useShow hook, not useForm. It is used to customize the error notification when data fetching fails. You can find more information about it in the useShow documentation (https://refine.dev/docs/data/hooks/use-show#errornotification). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai7mo ago
<@1085845877043769344> kapa.ai is still learning and improving, please let us know how it did by reacting below
extended-salmon
extended-salmon7mo ago
Hey @MajorD, passing errorNotification to the form is one way to achieve that. errorNotification expects you to pass an object or a function that returns an object with interface OpenNotificationParams If you pass a function you will also receive the error returned from the data provider as the first argument. You can also configure your data provider to match HttpError interface when throwing errors, then Refine will use the error.message and error.statusCode to display the notification. Interface references: OpenNotificationParams https://refine.dev/docs/core/interface-references/#opennotificationparams HttpError https://refine.dev/docs/core/interface-references/#httperror - just pasting the comment i've wrote in the #general 😅 -