Improve error handling by creating a function handler for connections on servers that use KY, and use the status key in the response as the key to success instead of catch. Use catch if an error occurs between the client and server, not between the server and backend.
27 lines
472 B
TypeScript
27 lines
472 B
TypeScript
"use server";
|
|
|
|
import { HTTPError } from "ky";
|
|
|
|
export const apiErrorHandler = async (
|
|
error: unknown,
|
|
safeFail: boolean = false
|
|
) => {
|
|
if (error instanceof HTTPError) {
|
|
return {
|
|
success: false,
|
|
status: error.response.status,
|
|
text: await error.response.json(),
|
|
};
|
|
}
|
|
|
|
if (safeFail) {
|
|
return {
|
|
success: false,
|
|
status: 500,
|
|
text: { message: "An unexpected error occurred" },
|
|
};
|
|
} else {
|
|
throw error;
|
|
}
|
|
};
|