wise-white
wise-white4w ago

How to catch error from Form Antd ?

How to catch error from Form Antd ?
5 Replies
kapa.ai
kapa.ai4w ago
Hi @tingadev. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To catch errors from a Form in Ant Design when using refine, you can utilize several methods depending on the context of the error. Here are some approaches based on the provided knowledge sources: 1. Using onMutationError in useForm The onMutationError callback in useForm is called after a mutation fails. This can be useful for catching errors during form submission.
useForm({
onMutationError: (data, variables, context, isAutoSave) => {
console.log({ data, variables, context, isAutoSave });
},
});
useForm({
onMutationError: (data, variables, context, isAutoSave) => {
console.log({ data, variables, context, isAutoSave });
},
});
Source (https://refine.dev/docs/ui-integrations/ant-design/hooks/use-form/#onmutationerror) 2. Customizing Error Notifications with errorNotification You can customize the error notification that pops up after form submission fails using the errorNotification property in useForm.
useForm({
action: "create",
resource: "post",
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when deleting ${data.id}`,
description: "Error",
type: "error",
};
},
});
useForm({
action: "create",
resource: "post",
errorNotification: (data, values, resource) => {
return {
message: `Something went wrong when deleting ${data.id}`,
description: "Error",
type: "error",
};
},
});
Source (https://refine.dev/docs/ui-integrations/ant-design/hooks/use-form/#errornotification) 3. Handling Errors in onFinish If you have a custom handleOnFinish method, you can wrap it in a try...catch block to handle errors and display notifications using the useNotification hook.
const handleOnFinish = async (values) => {
try {
// Your custom logic
await onFinish({
fullName: `${values.name} ${values.surname}`,
});
} catch (error) {
// Handle error
notification.error({
message: 'Error',
description: error.message,
});
}
};
const handleOnFinish = async (values) => {
try {
// Your custom logic
await onFinish({
fullName: `${values.name} ${values.surname}`,
});
} catch (error) {
// Handle error
notification.error({
message: 'Error',
description: error.message,
});
}
};
Source (https://github.com/refinedev/refine/issues/6171) 4. Using validateFields for Step Forms For step forms, you can use validateFields to catch validation errors before proceeding to the next step.
<Button
onClick={() => {
form.validateFields()
.then(() => gotoStep(current + 1))
.catch((error) => {
// Handle error
console.error(error);
});
}}
>
Next
</Button>
<Button
onClick={() => {
form.validateFields()
.then(() => gotoStep(current + 1))
.catch((error) => {
// Handle error
console.error(error);
});
}}
>
Next
</Button>
Source (https://github.com/refinedev/refine/issues/4621) 5. Handling Server-Side Validation Errors For server-side validation errors, ensure your dataProvider returns a rejected promise with an errors field. The useForm hook will automatically update the error state with the rejected errors field.
npm create refine-app@latest -- --example server-side-form-validation-antd
npm create refine-app@latest -- --example server-side-form-validation-antd
Source (https://refine.dev/docs/examples/form/antd/serverSideFormValidation/) By using these methods, you can effectively catch and handle errors in Ant Design forms when using refine. For more detailed examples and documentation, you can refer to the refine documentation (https://refine.dev/docs/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4w ago
<@761921731505946634> kapa.ai is still learning and improving, please let us know how it did by reacting below
wise-white
wise-white4w ago
@kapa.ai, How to catch error from field of Form Antd ?
kapa.ai
kapa.ai4w ago
Let me check the knowledge base for you. One moment! :books: ---------------------- To catch errors from a specific field in an Ant Design Form when using refine, you can use the rules property of the Form.Item component to define validation rules. Additionally, you can handle server-side validation errors by ensuring your dataProvider returns errors in a specific format. Here are the steps and examples: 1. Client-Side Validation with rules Property You can define validation rules directly in the Form.Item component using the rules property. This allows you to catch and display errors for specific fields.
import { Form, Input } from "antd";

<Form>
<Form.Item
label="Title"
name="title"
rules={[
{ required: true, message: "Title is required" },
{ min: 5, message: "Title must be at least 5 characters" },
]}
>
<Input />
</Form.Item>
...
</Form>
import { Form, Input } from "antd";

<Form>
<Form.Item
label="Title"
name="title"
rules={[
{ required: true, message: "Title is required" },
{ min: 5, message: "Title must be at least 5 characters" },
]}
>
<Input />
</Form.Item>
...
</Form>
Source (https://refine.dev/docs/advanced-tutorials/forms/custom-form-validation/) 2. Custom Validation with validator Function For more complex validation logic, you can use the validator function within the rules property.
<Form>
<Form.Item
label="Title"
name="title"
rules={[
{
validator: async (_, value) => {
if (!value || value.length < 5) {
return Promise.reject(new Error("Title must be at least 5 characters"));
}
// Add custom validation logic here
return Promise.resolve();
},
},
]}
>
<Input />
</Form.Item>
...
</Form>
<Form>
<Form.Item
label="Title"
name="title"
rules={[
{
validator: async (_, value) => {
if (!value || value.length < 5) {
return Promise.reject(new Error("Title must be at least 5 characters"));
}
// Add custom validation logic here
return Promise.resolve();
},
},
]}
>
<Input />
</Form.Item>
...
</Form>
Source (https://refine.dev/docs/examples/form/antd/custom-form-validation/) 3. Server-Side Validation To handle server-side validation errors, ensure your dataProvider returns a rejected promise with an errors field. The useForm hook will automatically update the error state with the rejected errors field.
import { HttpError } from "@refinedev/core";

const error: HttpError = {
message: "An error occurred while updating the record.",
statusCode: 400,
errors: {
title: ["Title is required"],
content: {
key: "form.error.content",
message: "Content is required.",
},
tags: true,
},
};
import { HttpError } from "@refinedev/core";

const error: HttpError = {
message: "An error occurred while updating the record.",
statusCode: 400,
errors: {
title: ["Title is required"],
content: {
key: "form.error.content",
message: "Content is required.",
},
tags: true,
},
};
Source (https://refine.dev/docs/guides-concepts/forms/#server-side-validation-) 4. Using setFields Method You can programmatically set errors on specific fields using the setFields method of the FormInstance.
import { Form } from "antd";

const form = Form.useFormInstance();

const setErrors = (errorData) => {
Object.entries(errorData).forEach(([field, errors]) => {
form.setFields([{ name: field, errors: errors ?? [] }]);
});
};

// Example usage
setErrors({
title: ["Title is required"],
content: ["Content is required"],
});
import { Form } from "antd";

const form = Form.useFormInstance();

const setErrors = (errorData) => {
Object.entries(errorData).forEach(([field, errors]) => {
form.setFields([{ name: field, errors: errors ?? [] }]);
});
};

// Example usage
setErrors({
title: ["Title is required"],
content: ["Content is required"],
});
Source (https://github.com/refinedev/refine/issues/2131) By using these methods, you can effectively catch and handle errors for specific fields in Ant Design forms when using refine. For more detailed examples and documentation, you can refer to the refine documentation (https://refine.dev/docs/). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4w ago
<@761921731505946634> kapa.ai is still learning and improving, please let us know how it did by reacting below