Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Exception from './exception'
- // fetch - обертка над window.fetch (параметры смотреть в Fetch API).
- // Возвращает распарсенный обьект данных с сервера, либо Exception
- // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
- export default async function (url, query) {
- try {
- let response
- try {
- response = await window.fetch(url, query)
- switch (response.status) {
- case 200:
- try {
- let contentType = response.headers.get('content-type')
- if (contentType) {
- if (contentType.includes('application/json')) {
- try {
- return await response.json()
- } catch (JSONError) { throw new Exception('software', 'JSON parse error') }
- // Other content-types
- } else { throw new Exception('software', 'Server response content-type error') }
- } else { throw new Exception('software', 'Response from server without content-type') }
- } catch (softwareException) { throw softwareException }
- case 500:
- throw new Exception('software', 'Internal server error.')
- case 400:
- throw new Exception('valid', 'Invalid fetching data. Please check your username and password.')
- case 401:
- throw new Exception('login', 'Bad login data. Please check your username and password.')
- case 403:
- throw new Exception('software', 'This errors must not exist')
- case 404:
- throw new Exception('software', 'Invalid exemplar of data model')
- default:
- throw new Exception('software', 'Unknown error with transfering data from server.')
- }
- } catch (error) { throw error }
- } catch (fetchError) {
- throw fetchError
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement