-
Notifications
You must be signed in to change notification settings - Fork 7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix: ошибка 500 при сабмите формы отправки пьесы #488
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -152,16 +152,17 @@ const Participation = () => { | |
|
||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { | ||
event.preventDefault(); | ||
if (canSubmit) { | ||
try { | ||
await postParticipation(form.values); | ||
} catch (error) { | ||
handleSubmitError(error); | ||
|
||
try { | ||
await postParticipation(form.values); | ||
} catch (error) { | ||
handleSubmitError(error); | ||
return; | ||
} | ||
|
||
return; | ||
router.push('/form/success'); | ||
} | ||
|
||
router.push('/form/success'); | ||
}; | ||
|
||
const canSubmit = !form.nonFieldError | ||
|
@@ -246,6 +247,7 @@ const Participation = () => { | |
<PhoneNumberInput | ||
value={form.values.phoneNumber} | ||
errorText={form.touched.phoneNumber ? form.errors.phoneNumber : ''} | ||
onChange={(value) => form.setFieldValue('phoneNumber', '+7' + value)} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Будет лучше если вынести в отдельную функцию - в какой-нить handle... There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ну тут я по аналогии со всеми остальными инпутами сделал, для всех остальных инпутов тогда тоже отдельные хендлеры прописать? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. да, давай |
||
/> | ||
</FormField> | ||
</Form.Field> | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Все хорошо, только можно упростить убрав лишний return
if (!canSubmit) return;
и router.push('/form/success') убрать в try
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
router.push('/form/success') убирать в try не вижу смысла, тогда редирект на страницу success произойдет, даже если запрос выполнится с ошибкой, можно добавить в блок finally, но тогда придется добавлять условие на случай ошибки. Сейчас реализовано корректно, на мой взгляд, т. к. в блоке catch есть return, т. е. если запрос выполнится с ошибкой редиректа на страницу success не будет.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
"тогда редирект на страницу success произойдет, даже если запрос выполнится с ошибкой" - если запрос выполняется с ошибкой, то он должен попадать в блок catch
"блоке catch есть return, т. е. если запрос выполнится с ошибкой редиректа на страницу success не будет" - ты же говоришь, что при ошибке запроса произойдет редирект на success в блоке catch!? если я правильно тебя понял, то тут противоречия
эти два блока кода, абсолютно одинаковы по функциональности, но второй вариант предпочтительнее, читаемостью и структурой
`const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
if (canSubmit) {
try {
await postParticipation(form.values);
} catch (error) {
handleSubmitError(error);
};
};`
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Как ты проверял? опиши свои кейсы
"а как появится ошибка, если не выполнится блок try?" - этот момент не очень понял
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
сорян, да действительно я ошибался, сейчас еще раз перепроверил... Видимо в прошлый раз строчку router.push('/form/success'); ставил выше запроса и не обратил на это внимания, все поправил, изменения запушил
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
еще раз извиняюсь, не внимательный)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я понял почему у меня отрабатывал router.push('/form/success'); в блоке try, даже, если запрос выполнялся с ошибкой, router.push у меня стоял после запроса, но в handleResponse в fetcher.ts был блок try catch и в catch было return err из-за этого в компоненте form.tsx при сабмите формы я вообще не попадал в блок catch, не важно с ошибкой выполнился запрос или нет...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
`async function handleResponse(response: Response) {
let payload;
try {
payload = await response.json();
} catch (err) {
// Если возникла ошибка при попытке разобрать JSON, устанавливаем payload в пустой объект
payload = {};
}
if (!response.ok) {
throw new HttpRequestError({ statusCode: response.status, payload });
}
return payload as T;
}`
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В общем так как if (!response.ok) {
throw new HttpRequestError({ statusCode: response.status, payload });
} это ошибка выбраcывалась в блоке try, поэтому оно дальше попадало в catch который в handleResponse и дальше просто return error, которое кидало в try handleSubmit
Вот сверху вариант должен работать правильно, проверяй