Added form error hanlder

This commit is contained in:
sianida26 2024-05-08 00:39:15 +07:00
parent 199758150d
commit 5e36b3af26
4 changed files with 42 additions and 7 deletions

View File

@ -10,7 +10,7 @@ class DashboardError extends Error {
"CRITICAL";
constructor(options: DashboardErrorParameter) {
super();
super(options.message);
this.errorCode = options.errorCode;
this.statusCode = options.statusCode ?? this.statusCode;

View File

@ -0,0 +1,15 @@
class FormResponseError extends Error {
public readonly message: string;
public readonly formErrors: Record<string, string>;
constructor(message: string, formErrors: Record<string, string>) {
super(message);
this.message = message;
this.formErrors = formErrors;
Object.setPrototypeOf(this, new.target.prototype);
}
}
export default FormResponseError;

View File

@ -19,6 +19,7 @@ import { TbDeviceFloppy } from "react-icons/tb";
import client from "../../../honoClient";
import { useEffect } from "react";
import { notifications } from "@mantine/notifications";
import FormResponseError from "@/errors/FormResponseError";
const routeApi = getRouteApi("/_dashboardLayout/users/");
@ -82,11 +83,19 @@ export default function UserFormModal() {
? await updateUser(options.data)
: await createUser(options.data);
},
onError: (error) => {
try {
form.setErrors(JSON.parse(JSON.parse(error.message).message));
} catch (e) {
console.error(e);
onError: (error: unknown) => {
console.log(error);
if (error instanceof FormResponseError) {
form.setErrors(error.formErrors);
return;
}
if (error instanceof Error) {
notifications.show({
message: error.message,
color: "red",
});
}
},
});

View File

@ -1,3 +1,4 @@
import FormResponseError from "@/errors/FormResponseError";
import { ClientResponse } from "hono/client";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -21,7 +22,17 @@ async function fetchRPC<T>(
//TODO: Add error reporting
const data = (await res.json()) as unknown as { message?: string };
const data = (await res.json()) as unknown as {
message?: string;
formErrors?: Record<string, string>;
};
if (res.status === 422 && data.formErrors) {
throw new FormResponseError(
data.message ?? "Something is gone wrong",
data.formErrors
);
}
throw new Error(data.message ?? "Something is gone wrong");
}