forked from tanner/qotnews
fix: Improve submit error handling on API and refactor client with async/await
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
This commit is contained in:
@@ -6,7 +6,7 @@ function Submit() {
|
||||
const inputRef = useRef(null);
|
||||
const history = useHistory();
|
||||
|
||||
const submitArticle = (event) => {
|
||||
const submitArticle = async (event) => {
|
||||
event.preventDefault();
|
||||
const url = event.target[0].value;
|
||||
inputRef.current.blur();
|
||||
@@ -16,31 +16,25 @@ function Submit() {
|
||||
let data = new FormData();
|
||||
data.append('url', url);
|
||||
|
||||
fetch('/api/submit', { method: 'POST', body: data })
|
||||
.then(res => {
|
||||
if (res.ok) {
|
||||
return res.json().then(data => ({ ok: true, data: data }));
|
||||
try {
|
||||
const res = await fetch('/api/submit', { method: 'POST', body: data });
|
||||
|
||||
if (res.ok) {
|
||||
const result = await res.json();
|
||||
history.replace('/' + result.nid);
|
||||
} else {
|
||||
let errorData;
|
||||
try {
|
||||
errorData = await res.json();
|
||||
} catch (jsonError) {
|
||||
// Not a JSON error from our API, so it's a server issue
|
||||
throw new Error(`Server responded with ${res.status} ${res.statusText}`);
|
||||
}
|
||||
// Handle error responses
|
||||
return res.json()
|
||||
.then(data => ({ ok: false, data: data })) // Our API's JSON error
|
||||
.catch(() => {
|
||||
// Not a JSON error from our API, so it's a server issue
|
||||
throw new Error(`Server responded with ${res.status} ${res.statusText}`);
|
||||
});
|
||||
})
|
||||
.then(
|
||||
({ ok, data }) => {
|
||||
if (ok) {
|
||||
history.replace('/' + data.nid);
|
||||
} else {
|
||||
setProgress(data.error || 'An unknown error occurred.');
|
||||
}
|
||||
},
|
||||
(error) => {
|
||||
setProgress(`Error: ${error.toString()}`);
|
||||
}
|
||||
);
|
||||
setProgress(errorData.error || 'An unknown error occurred.');
|
||||
}
|
||||
} catch (error) {
|
||||
setProgress(`Error: ${error.toString()}`);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user