How to return a specific error message from the backend server for the resource update / create?

Hi, I'm using @nestjsx/crud adapter with Refine. What I want to do is that I want to rewrite some of the services and provide a meaningful error message when there's some validation errors on the backend, and show it on the front-end after saving the content. Is that doable?
kapa.ai
kapa.ai119d ago
Hi @Eric Hu. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Yes, it's definitely doable. Refine supports server-side validation out-of-the-box in all useForm derivatives. To handle server-side validation, the data providers need to be correctly set up to return the errors in form submissions with a specific format. After this, Refine's useForm will propagate the errors to the respective form fields. Here's an example of how you can return a specific error message from the backend:
import { HttpError } from "@refinedev/core";

const error: HttpError = {
message: "An error occurred while updating the record.",
statusCode: 400,
// the errors field is required for server-side validation.
// when the errors field is set, useForm will automatically display the error messages in the form with the corresponding fields.
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,
// the errors field is required for server-side validation.
// when the errors field is set, useForm will automatically display the error messages in the form with the corresponding fields.
errors: {
title: ["Title is required"],
content: {
key: "form.error.content",
message: "Content is required.",
},
tags: true,
},
};
In this example, the errors field is required for server-side validation. When the errors field is set, useForm will automatically display the error messages in the form with the corresponding fields. The message field is the error message that you want to display. For more information, you can check out the Refine documentation on server-side validation (https://refine.dev/docs/guides-concepts/forms#server-side-validation-). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai119d ago
<@454649036289343500> kapa.ai is still learning and improving, please let us know how it did by reacting below
metropolitan-bronze
metropolitan-bronze119d ago
Thanks, I think it should work. However, how can I use it with @nestjsx/crud? I tried this but it doesn't work:
async createOne(req: CrudRequest, dto: DeepPartial<QuestionTypeEntity>): Promise<QuestionTypeEntity> {
return Promise.reject({
message: 'This is an error from the server',
statusCode: 403,
errors: {
name: 'Name should be at least 3 characters long',
},
})
// return super.createOne(req, dto)
}
async createOne(req: CrudRequest, dto: DeepPartial<QuestionTypeEntity>): Promise<QuestionTypeEntity> {
return Promise.reject({
message: 'This is an error from the server',
statusCode: 403,
errors: {
name: 'Name should be at least 3 characters long',
},
})
// return super.createOne(req, dto)
}
No description
No description
metropolitan-bronze
metropolitan-bronze119d ago
@kapa.ai How to use the code you showed me above? Should I install @refinedev/core on my backend?
kapa.ai
kapa.ai119d ago
Let me check the knowledge base for you. One moment! :books: ---------------------- No, you don't need to install @refinedev/core on your backend. The code I provided was just an example of the structure that your backend should return when a validation error occurs. In your NestJS service, when a validation error occurs, you should throw an HttpException with a similar structure. Here's an example:
throw new HttpException({
message: 'An error occurred while updating the record.',
errors: {
title: 'Title is required',
content: 'Content is required',
},
}, HttpStatus.BAD_REQUEST);
throw new HttpException({
message: 'An error occurred while updating the record.',
errors: {
title: 'Title is required',
content: 'Content is required',
},
}, HttpStatus.BAD_REQUEST);
In this example, HttpException is a class from @nestjs/common and HttpStatus is an enum from the same package. The errors object keys should match the names of your form fields. The error messages you provide here will be displayed next to the corresponding form fields in the Refine form. Remember, the key point here is that your backend needs to return the errors in the mutation response with the expected format for Refine to handle them correctly. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai119d ago
<@454649036289343500> kapa.ai is still learning and improving, please let us know how it did by reacting below
metropolitan-bronze
metropolitan-bronze119d ago
@kapa.ai Is there any example with Nest.js? I tried this but it doesn't work:
async createOne(req: CrudRequest, dto: DeepPartial<QuestionTypeEntity>): Promise<QuestionTypeEntity> {
throw new HttpException(
{
message: 'An error occurred while updating the record.',
errors: {
name: 'Error!',
},
},
HttpStatus.BAD_REQUEST
)
}
async createOne(req: CrudRequest, dto: DeepPartial<QuestionTypeEntity>): Promise<QuestionTypeEntity> {
throw new HttpException(
{
message: 'An error occurred while updating the record.',
errors: {
name: 'Error!',
},
},
HttpStatus.BAD_REQUEST
)
}
kapa.ai
kapa.ai119d ago
Let me check the knowledge base for you. One moment! :books: ---------------------- I'm sorry, but based on the information extracts provided, there isn't a specific example of handling server-side validation errors with Nest.js and Refine. However, the code you've shared seems correct in terms of throwing an HttpException with a specific error message. If it's not working as expected, the issue might be somewhere else in your code or it could be related to how the error is handled on the frontend with Refine. Refine expects errors to be in a specific format to handle them correctly. The errors object in the response should have keys that match the names of your form fields. The error messages you provide here will be displayed next to the corresponding form fields in the Refine form. If you're still having trouble, I would recommend checking the Refine documentation (https://refine.dev/docs) and Nest.js documentation (https://docs.nestjs.com/exception-filters) for more information on error handling. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai119d ago
<@454649036289343500> kapa.ai is still learning and improving, please let us know how it did by reacting below
metropolitan-bronze
metropolitan-bronze119d ago
It turned out that the adapter of @nestjsx/crud has got some issues with server error handling. I forked it and rewrote this part. And it works now.
extended-salmon
extended-salmon119d ago
Hello @Eric Hu happy to see you fixed the issue, would you like to create a PR for this one?
More Posts
How to hide resource from sidebarHow can I hide a menu item from sidebar resource? I want to hide some particular menu links from myAdd a a POST api call on an a page when editThanks for an awsome framework. I have a page where i do some edits on some fields. Now I also need Crud api headerHow can i add a auth token to the header that i call if i use infencerSupabase and RBACHow to implement supabase and RBAC in refine?Group Nav buttons in a bulk buttonHi in the CRUD App is there a way to Group Nav buttons in a bulk button that hide and reveal subbuttSupabase- Ability for admin user to add usersHi everyone, I have a client who's plan for a crud app is to disable user signup as it'll be an inteHow to load a component both in Authenticated and Unauthenticated state?How can I arrange my routes to load a component page both in authenticated and unathenticated state?crud operator for text[]Hi guys, I can't filter my field I have a field name superfood which is a text array in supabase db Nextjs app routerHow setup refine using the latest nextjs app router and shadcn uiWhen sidebar is collapsed, changing page on paginated list open sidebar menu itemWhen changing the page, the page and offset query parameter of path is modified and is detected as aUseMany missing in some generated pages by the MUIinferencerWhats the reason why some List pages are generated by the MUIinferencer with the UseMany methods andgraphql mutationi am using graphql for and i want to pass different meta fields for getOne and update using useForm Filter a table field with outside component and stateHi guys, I'm using useTable to get data from database, here is my useTable code ```const filter = sugraphql mutationI am trying to use useForm from ``` import { useForm } from "@refinedev/react-hook-form"; ``` i waUpdate specific field by using mutate useUpdateHi guys, I'm using mutate of useUpdate() to update a record on my db How can I just update a specifiedit modalI am trying to create a edit modal inside the card. my card contains only name which can be edited oHiding a button in the Navbar based on User Role (MUI)Hi, How can i hide a button in the Nav bar based on the role of the user connected? (MUI)Filtering with useList and state operationHi guys, I currently have a List with useList to get data from a table with supabase Now I have a buHow does useLogin with custom authProvider?I want use custom authProvider and login.include options in useManylike pagination how to add include method in useTable hooks or any other hooks?