Originally created utils file for signup with the following functions:
src/components/site/signup/utils.ts
setYupErrors()
handleApiResponse()
handleValidationError()
handleApiResponseWithState()
then decided they could be useful throughout the app, broke up the following functions into the following files/folders:
src/utils/apiValidationHandlerUtils.ts
setYupErrors()
normalizeApiErrors()
handleValidationError()
src/utils/apiResponseHandlerUtils.ts
apiResponseHandlerUtils.ts
src/components/site/signup/utils.ts
handleApiResponseWithState()
With assistance from you before, we changed setYupErrors() and handleValidationError from:
export function setYupErrors(validationError: any, setFormValidationErrors: Dispatch)
{
if (validationError.inner)
{
const yupErrors: Record<string, string[]> = {};
validationError.inner.forEach((error: any) =>
{
if (!yupErrors[error.path])
{
yupErrors[error.path] = [];
}
yupErrors[error.path].push(error.message);
});
console.log('Yup Errors:', yupErrors);// TODO <-- CHANGE DEBUG CONSOLE TO LOGGER
setFormValidationErrors(yupErrors);
}
else
{
console.warn('ValidationError has no inner array:', validationError);// TODO <-- CHANGE DEBUG CONSOLE TO LOGGER
setFormValidationErrors({});
}
}
export function handleValidationError(
error: any,
setErrorMessage: Dispatch<SetStateAction<string | null>>,
setFormValidationErrors: Dispatch<SetStateAction<Record<string, any>>>
): void
{
console.log('handleValidationError called with:', error);// TODO <-- CHANGE DEBUG CONSOLE TO LOGGER
if (error.name === 'ValidationError')
{
console.log('Detected Yup ValidationError', error.inner);// TODO <-- CHANGE DEBUG CONSOLE TO LOGGER
if (error.inner && error.inner.length > 0)
{
setYupErrors(error, setFormErrors);
setError(error.inner[0].message);// set first validation error as general error message
}
else
{
setErrorMessage(error.message);
setFormValidationErrors({});
}
}
else
{
// Fallback: set error message from API or unknown error
setErrorMessage(error.message || 'Unknown error occurred');
}
}
To:
export function setYupErrors(
validationError: yup.ValidationError,
setFormValidationErrors: Dispatch<SetStateAction>
): void
{
if (validationError?.inner && Array.isArray(validationError.inner))
{
const yupErrors: ApiErrorDetail = {};
we can still export setYupErrors() for now, but newer handleValidationError() does not even use setYupErrors(). Also want to modern the functions and use newer calls to them const ().
Assistant
User
I would prefer to keep setYupErrors() and have handleValidationError() call setYupErrors()
Assistant
User
export const handleApiResponseWithState<Type = any> = (
response: GenericResponse,
setErrorMessage: Dispatch<SetStateAction<string | null>>,
setSuccessMessage: Dispatch<SetStateAction<string | null>>,
setFormValidationErrors: Dispatch<SetStateAction>,
setUserId: Dispatch<SetStateAction<number | null>>,
setUserToken: Dispatch<SetStateAction<string | null>>,
setStep: Dispatch<SetStateAction>,
// "nextStepMap" - Used as map for setting steps calls from backend data array next_step
nextStepMap: Record<string, number> =
{
email_verification: 1,
password_setup: 2,
business_category: 3,
// add other mappings if needed
}
): boolean =>
{
Great, you're correctly running Yup validation before proceeding. However, your snippet is missing the early return after the validation error, so even if validation fails, your code likely continues to do the API call.
What you need to do:
Just add a return immediately after calling to prevent further execution if validation fails:
Yes! The long stack trace you’re seeing is because you’re logging the entireValidationError object (which includes its stack).
To log only the message (e.g. ValidationError: Invalid email) without the stack trace, you should log the .message property of the error rather than the whole error object.
export function normalizeApiErrors(errors: any): ApiErrorDetail
{
if (!errors || typeof errors !== 'object')
{
return {};
}
const normalized: ApiErrorDetail = {};
Object.entries(errors).forEach(([field, value]) =>
{
if (Array.isArray(value))
{
const filtered = value.filter((msg) => typeof msg === 'string' && msg.trim() !== '');
normalized[field] = filtered.length === 1 ? filtered[0] : filtered;
}
else if (typeof value === 'string' && value.trim() !== '')
{
normalized[field] = value;
}
else
{
/**
* If value is something else (object etc.), ignore or transform as needed
* For now, ignore silently
*/
console.log('Normalize Api Error - Unexpected value:', value);//<!-- TODO Console/Logger Debug
//logger.log('Normalize Api Error - Unexpected value:', value);
}
});
return normalized;
}
export function handleValidationError
(
error: any,
setErrorMessage: Dispatch<SetStateAction<string | null>>,
setFormValidationErrors: Dispatch<SetStateAction>,
emitGlobalAlert: boolean = true// default param to allow skipping alert if needed
): void
{
// Yup validation error path
if (error?.name === 'ValidationError' && Array.isArray(error.inner))
{
const validationErrors: ApiErrorDetail = {};
error.inner.forEach((errorItem: any) =>
{
if (errorItem.path && !(errorItem.path in validationErrors))
{
validationErrors[errorItem.path] = errorItem.message;
}
});
setFormValidationErrors(validationErrors);
const firstErrorMessage = error.inner.length > 0 ? error.inner[0].message : error.message;
setErrorMessage(firstErrorMessage);
if (emitGlobalAlert)
{
emitEvent('alert', { type: 'danger', message: firstErrorMessage });
}
console.warn('Yup validation error:', error);//<!-- TODO Console/Logger Debug
//logger.warn('Yup validation error:', error);
}
// API validation error response path
else if (error?.errors && typeof error.errors === 'object')
{
// Backend or API validation errors (expected to be ApiErrorDetail shape or close)
const normalizedErrors = normalizeApiErrors(error.errors);
setFormValidationErrors(normalizedErrors);
// Derive general message from API response message or first field error
const generalErrorMessage = typeof error.message === 'string' && error.message.trim() !== ''
? error.message : Object.values(normalizedErrors)[0] ?? 'Validation failed';
setErrorMessage(generalErrorMessage);
if (emitGlobalAlert)
{
emitEvent('alert', { type: 'danger', message: generalErrorMessage });
}
console.warn('API validation error:', error);//<!-- TODO Console/Logger Debug
//logger.warn('API validation error:', error);
}
// Unknown/error fallback
else
{
// Other kinds of errors (network, unknown, etc.)
const fallbackErrorMessage = error?.message || 'An unknown error occurred.';
setErrorMessage(fallbackErrorMessage);
setFormValidationErrors({});
if (emitGlobalAlert)
{
emitEvent('alert', { type: 'danger', message: fallbackErrorMessage });
}
console.error('Unhandled error:', error);//<!-- TODO Console/Logger Debug
//logger.error('Unhandled error:', error);
}
}
Im thinking setYupErrors should not be exported, it should only be handled by handleValidationError as it is orignally. What do you think?
You make a good point. Here’s a breakdown of considerations regarding exporting setYupErrors() vs. keeping it internal within handleValidationError():
Pros of keeping setYupErrors() internal (not exported):
Encapsulation & abstraction:
If setYupErrors() is only relevant as a helper function inside handleValidationError(), hiding it reduces the exported API surface and prevents misuse or complexity leaking outside.
Less duplication and potential inconsistent usage:
By centralizing Yup validation error handling inside handleValidationError(), you ensure consistent handling of errors and error state updates throughout the app.
Simplifies external contract:
Only expose the main function you want consumers to call, i.e., handleValidationError(), making the utils API easier to understand and use.
Easier refactoring:
You can freely change setYupErrors() implementation or signature later without impacting other modules.
Pros of exporting setYupErrors() separately:
Reusability for specialized cases:
There might be certain places in the app where a Yup validation error needs to be handled differently or where developers want to just set the form validation errors without the full handleValidationError() boilerplate.
Separation of concerns: setYupErrors() is a narrowly focused function that simply sets form errors from a yup.ValidationError. Exporting it separately could make it easier to use in more "manual" or customized flows (e.g., if you want to override or extend the general logic).
Unit testing:
Exporting individual functions can help facilitate isolated unit tests of the small parts too.
My Recommendation
If you don’t currently have or foresee a use case that requires only setting Yup errors without the generalized handleValidationError() logic, keep setYupErrors() private inside the module and only export handleValidationError().
You can still keep setYupErrors() as a named function within the module (for clarity and testability), but don’t export it.
This aligns with your original plan — have one utility handleValidationError() that abstracts the error handling for any validation errors (including Yup), and internally call setYupErrors() as a helper.
If later you discover setYupErrors() as useful elsewhere, you could always export it then. This is easier than removing exports later.
Example:
// apiValidationHandlerUtils.ts
function setYupErrors(
validationError: yup.ValidationError,
setFormValidationErrors: Dispatch<SetStateAction<ApiErrorDetail>>
): void {
// Implementation...
}
export function handleValidationError(
error: any,
setErrorMessage: Dispatch<SetStateAction<string | null>>,
setFormValidationErrors: Dispatch<SetStateAction<ApiErrorDetail>>,
emitGlobalAlert = true
): void {
if (error?.name === 'ValidationError' && Array.isArray(error.inner)) {
setYupErrors(error, setFormValidationErrors);
// Further logic...
}
// other cases...
}
Bonus: If you want, you can also provide a single handleValidationError export and a private helper inside the module:
Enforces one way to handle validation errors consistently.
Reduces cognitive load and helps future maintainers (including yourself).
TL;DR
Yes, I agree with your thought that setYupErrors() should typically be private/internal and only invoked by handleValidationError().
This fits with common best practices about reducing the public API of utilities and keeping helpers internal unless explicitly required elsewhere.
If you want, I can help you refactor the code for that or write test cases that suit this pattern!
Good points:
Your current handleValidationError() doesn't call setYupErrors() anymore — it directly processes Yup errors internally and sets the form errors. That makes setYupErrors() somewhat redundant, or at least an alternative implementation.
You want to modernize by using consistent modern syntax — e.g., define functions as const functionName = (...) => { ... } rather than function functionName(...) { ... }.
Suggested modernization
Wrap everything as arrow functions assigned to consts for consistency.
Maintain export of setYupErrors() if you want, but:
Add JSDoc comments for clarity;
Possibly mark setYupErrors() as “deprecated” (in comment) or note only to use if needed separately;
Have handleValidationError() fully self-contained (as it is now).
Example refactor of your utils (using const and arrow functions):
import { Dispatch, SetStateAction } from 'react';
import * as yup from 'yup';
import { ApiErrorDetail } from './types'; // assuming you have this type somewhere
import { emitEvent } from './eventBus'; // example for emitEvent, adjust accordingly
/**
* Sets Yup validation errors into form error state
* @param validationError Yup.ValidationError instance
* @param setFormValidationErrors React state setter for form errors
*/
export const setYupErrors = (
validationError: yup.ValidationError,
setFormValidationErrors: Dispatch<SetStateAction<ApiErrorDetail>>
): void => {
if (validationError?.inner && Array.isArray(validationError.inner)) {
const yupErrors: ApiErrorDetail = {};
validationError.inner.forEach((errorItem) => {
if (errorItem.path) {
const existing = yupErrors[errorItem.path];
if (existing === undefined) {
yupErrors[errorItem.path] = errorItem.message;
} else if (Array.isArray(existing)) {
existing.push(errorItem.message);
} else {
yupErrors[errorItem.path] = [existing, errorItem.message];
}
}
});
console.log('Yup validation errors:', yupErrors);
setFormValidationErrors(yupErrors);
} else {
console.warn(
'Yup ValidationError missing inner array or invalid format:',
validationError
);
setFormValidationErrors({});
}
};
/**
* Normalize error object returned by API to ApiErrorDetail
* @param errors The errors object from API
* @returns Normalized ApiErrorDetail
*/
export const normalizeApiErrors = (errors: any): ApiErrorDetail => {
if (!errors || typeof errors !== 'object') {
return {};
}
const normalized: ApiErrorDetail = {};
Object.entries(errors).forEach(([field, value]) => {
if (Array.isArray(value)) {
const filtered = value.filter(
(msg) => typeof msg === 'string' && msg.trim() !== ''
);
normalized[field] = filtered.length === 1 ? filtered[0] : filtered;
} else if (typeof value === 'string' && value.trim() !== '') {
normalized[field] = value;
} else {
console.log('Normalize Api Error - Unexpected value:', value);
}
});
return normalized;
};
/**
* Handles validation error uniformly across Yup or API validation errors
* @param error The error object potentially from Yup or API
* @param setErrorMessage React setter for general error message string
* @param setFormValidationErrors React setter for detailed field errors
* @param emitGlobalAlert Whether to emit a global alert event
*/
export const handleValidationError = (
error: any,
setErrorMessage: Dispatch<SetStateAction<string | null>>,
setFormValidationErrors: Dispatch<SetStateAction<ApiErrorDetail>>,
emitGlobalAlert = true
): void => {
if (error?.name === 'ValidationError' && Array.isArray(error.inner)) {
// Yup error handling in place of setYupErrors for direct control
const validationErrors: ApiErrorDetail = {};
error.inner.forEach((errorItem: any) => {
if (errorItem.path && !(errorItem.path in validationErrors)) {
validationErrors[errorItem.path] = errorItem.message;
}
});
setFormValidationErrors(validationErrors);
const firstErrorMessage =
error.inner.length > 0 ? error.inner[0].message : error.message;
setErrorMessage(firstErrorMessage);
if (emitGlobalAlert) {
emitEvent('alert', { type: 'danger', message: firstErrorMessage });
}
console.warn('Yup validation error:', error);
} else if (error?.errors && typeof error.errors === 'object') {
// API validation error from backend shape handling
const normalizedErrors = normalizeApiErrors(error.errors);
setFormValidationErrors(normalizedErrors);
const generalErrorMessage =
typeof error.message === 'string' && error.message.trim() !== ''
? error.message
: Object.values(normalizedErrors)[0] ?? 'Validation failed';
setErrorMessage(generalErrorMessage);
if (emitGlobalAlert) {
emitEvent('alert', { type: 'danger', message: generalErrorMessage });
}
console.warn('API validation error:', error);
} else {
// Fallback unknown error handling
const fallbackErrorMessage = error?.message || 'An unknown error occurred.';
setErrorMessage(fallbackErrorMessage);
setFormValidationErrors({});
if (emitGlobalAlert) {
emitEvent('alert', { type: 'danger', message: fallbackErrorMessage });
}
console.error('Unhandled error:', error);
}
};
Notes
Notice all funcs are const arrow functions for modern consistency;
Kept setYupErrors exported but unchanged internally;
Inline comments/JSDoc added for clarity and better maintainability;
handleValidationError() uses internal code instead of calling setYupErrors();
You can later revisit setYupErrors() export status without breaking changes.
If you want, I can also help convert your other utils or usage sites to use this updated style!
That makes perfect sense for code reuse and separation of concerns!
Having handleValidationError() call setYupErrors() is clean, easier to maintain, and reduces duplication.
handleValidationError() delegates Yup cases to setYupErrors() — no duplicated iteration logic.
It then proceeds to set the error message and optionally fire a global alert.
Keeps all functions modern with arrow function assigned to const.
setYupErrors remains exported and reusable independently if needed.
If you want, I can help you rewrite your imports/usage sites accordingly or write tests for these. Let me know!
The TypeScript parser is hitting an error at the type annotation on the parameter response: GenericResponse<Type> in your arrow function declaration.
Why?
When you write a const arrow function with a generic type, the generic cannot be specified on the variable itself, it must be specified on the function.
Please give that a try! It will fix the TypeScript syntax error. Let me know if you want me to help with the function implementation or other improvements too.
(2025-05-18T15:54:43.412Z) [Handle Api Response Error:] Validation failed. Please review the errors.
should not be able to go to the api call
Absolutely — if Yup validation fails, you want to stop the submission process immediately (i.e., no API call), and only proceed if the validation passes.
Where/how to do that?
The typical pattern is that you run your Yup validation logic before making the API call, using .validate() or .validateSync(). If validation fails, catch the error and handle it (set errors & message), then return early, prevent submission.
Example pattern in an async form submit handler:
import * as yup from 'yup';
// Your yup schema
const schema = yup.object({
email: yup.string().email('Invalid email').required('Email is required'),
// ... other fields
});
const onSubmit = async (formData) => {
try {
// Validate first
await schema.validate(formData, { abortEarly: false });
// If valid, clear errors
setFormValidationErrors({});
setErrorMessage(null);
// Proceed with API call
const response = await apiCall(formData);
handleApiResponseWithState(response, ...);
} catch (error) {
if (error instanceof yup.ValidationError) {
// Set Yup validation errors & message and stop submission
handleValidationError(error, setErrorMessage, setFormValidationErrors);
return; // EARLY RETURN: do NOT proceed to API call
} else {
// Other errors (network, unexpected)
setErrorMessage('An unexpected error occurred');
console.error(error);
}
}
};
Key points:
Use await schema.validate() (or .validateSync() with try/catch).
abortEarly: false so Yup collects all errors, not just the first.
If Yup throws a ValidationError, handle validation errors & return; — don’t continue to API call.
Only if validation passes do you continue with API call & further processing.
If you do validation in utils:
Example handleSubmit with your utils:
const onSubmit = async (formData) => {
try {
await signupSchema.validate(formData, { abortEarly: false });
setFormValidationErrors({});
setErrorMessage(null);
// Continue with API call and response handling
const response = await apiCall(formData);
handleApiResponseWithState(
response,
setErrorMessage,
setSuccessMessage,
setFormValidationErrors,
setUserId,
setUserToken,
setStep,
nextStepMap
);
} catch (error) {
if (error.name === 'ValidationError') {
handleValidationError(error, setErrorMessage, setFormValidationErrors);
return; // stop here — no API call
}
setErrorMessage('An unexpected error occurred');
}
};
Summary
Put Yup validation before API call.
Catch validation errors.
Call your handleValidationError() to set validation messages / fields.
Return early, do not proceed if validation fails.
If you want, I can help you refactor your current submit handler or utility calls to enforce this pattern — just share the relevant form submitting code!
handleValidationError()
try {
await stageSchemas[0].validate({ email: signupData.email }, { abortEarly: false });
setFormValidationErrors({});
} catch (error) {
handleValidationError(error, setErrorMessage, setFormValidationErrors, false);
return; // <<< Stop submission here if Yup validation fails
}
// Proceed with API call only if no validation errors
Why?
Without this return, the code continues running and calls your API, even when validation failed. The user then sees your Yup errors, but the app still makes a backend request, which you want to avoid.
Full minimal example for clarity:
async function submitStageZeroEmail() {
try {
await stageSchemas[0].validate({ email: signupData.email }, { abortEarly: false });
setFormValidationErrors({}); // clear old errors
// validation passed, continue with API call
const response = await apiCall(stageZeroEmailEndpoint, signupData);
// handle response, update UI etc.
handleApiResponseWithState(
response,
setErrorMessage,
setSuccessMessage,
setFormValidationErrors,
setUserId,
setUserToken,
setStep,
nextStepMap
);
} catch (error) {
if (error.name === 'ValidationError') {
// Set validation errors and STOP execution here:
handleValidationError(error, setErrorMessage, setFormValidationErrors, false);
return;
}
// Other unexpected errors
setErrorMessage('An unexpected error occurred.');
setFormValidationErrors({});
}
}
In brief:
Add return after handleValidationError() in your catch block to halt execution.
Then API call happens only if Yup validation passes.
Let me know if you want me to help plug this into your current handler code or refine any other part!
If you want the prefix "ValidationError: " included, simply: