'Handling 413 (Request Entity Too Large) error with try/catch
I am trying to figure out how to handle 413 error when uploading files, to show the user that the file they are trying to upload is too large
. I am uploading the files from a component in React using React-dropzone, then pass it to sagas, then a function in sagas will loop through the file and send each files to Rails - upload the files using Carrierwave then rails will send back some data if the upload success.
MyUploadComponent.jsx
this.state = {
files: [{file1}, {file2}, {file3}]
}
uploadFiles = () => {
this.props.saveFiles(this.state.files)
}
sagas.js
function* saveFiles(action){
let err = false
let completed;
const results = yield Promise.all(action.files.map(function(file){
return saveFile(file)
})).then(data => {
completed = data
})
yield put({
type: actionTypes.FILE_UPLOADED,
index: completed
})
}
function saveFile(file, cid, index){
try{
let formData = new FormData()
formData.append("file", file)
let result = fetch(URL,
{
method: "POST",
credentials: "same-origin",
body: formData
}).then(response => response.json()).then(function(data){
return data
})
return result
} catch(ex) { console.log(ex) }
}
When I am having 413 error, I also receive this additional message
Solution 1:[1]
I think you can just check reponse.status for deciding how to handle the response:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#response_objects
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | RobertG |