Improve fetch error handling

This commit is contained in:
Фролов 2021-10-11 13:41:54 +05:00
parent 9360724ad2
commit 0aacc05dac
3 changed files with 33 additions and 9 deletions

View File

@ -0,0 +1,7 @@
export class ErrorFetch extends Error {
constructor(status, message) {
super(message);
this.name = "ErrorFetch"
this.status = status
}
}

View File

@ -2,22 +2,38 @@ import { Upload, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { useState } from 'react'
import { upload } from './factory'
import { ErrorFetch } from './ErrorFetch'
export default function UploadForm({url, accept, onUploadStart, onUploadComplete, onUploadError}) {
export const UploadForm = ({url, accept, style, formData, onUploadStart, onUploadSuccess, onUploadComplete, onUploadError}) => {
const [fileList, setfileList] = useState([])
const handleFileSend = async (values) => {
const handleFileSend = async () => {
if(onUploadStart)
onUploadStart()
try {
const formData = new FormData()
const formDataLocal = new FormData()
fileList.forEach((val) => {
formData.append("files", val.originFileObj);
});
await upload(url, formData)
formDataLocal.append("files", val.originFileObj)
})
if(formData)
for(var propName in formData)
formDataLocal.append(propName, formData[propName])
const response = await upload(url, formDataLocal)
if(!response.ok)
{
const errorText = await response.text()
const error = new ErrorFetch(response.status, errorText)
throw error
}
else{
if(onUploadSuccess)
onUploadSuccess()
}
} catch(error) {
if(onUploadError)
onUploadError(error)
onUploadError(error)
} finally {
setfileList([])
if(onUploadComplete)
@ -27,7 +43,7 @@ export default function UploadForm({url, accept, onUploadStart, onUploadComplete
const isSendButtonEnabled = fileList.length > 0
return(
<div style={{display: 'flex'}}>
<div style={{display: 'flex', ...style}}>
<Upload
name ="file"
fileList={fileList}

View File

@ -81,13 +81,14 @@ export const download = async (url:string, fileName?:string) => {
}
export const upload = async (url:string, formData: FormData) => {
await fetch(url, {
let response = await fetch(url, {
headers: {
Authorization: 'Bearer ' + localStorage['token']
},
method: 'Post',
body: formData,
})
return response
}
export const downloadFile = async (fileInfo: FileInfoDto) => {