Advertisement
Guest User

Untitled

a guest
Nov 6th, 2017
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Exception from './exception'
  2.  
  3. // fetch - обертка над window.fetch (параметры смотреть в Fetch API).
  4. // Возвращает распарсенный обьект данных с сервера, либо Exception
  5. // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
  6.  
  7. export default async function (url, query) {
  8.   try {
  9.     let response
  10.     try {
  11.       response = await window.fetch(url, query)
  12.       switch (response.status) {
  13.         case 200:
  14.           try {
  15.             let contentType = response.headers.get('content-type')
  16.             if (contentType) {
  17.               if (contentType.includes('application/json')) {
  18.                 try {
  19.                   return await response.json()
  20.                 } catch (JSONError) { throw new Exception('software', 'JSON parse error') }
  21.                 // Other content-types
  22.               } else { throw new Exception('software', 'Server response content-type error') }
  23.             } else { throw new Exception('software', 'Response from server without content-type') }
  24.           } catch (softwareException) { throw softwareException }
  25.         case 500:
  26.           throw new Exception('software', 'Internal server error.')
  27.         case 400:
  28.           throw new Exception('valid', 'Invalid fetching data. Please check your username and password.')
  29.         case 401:
  30.           throw new Exception('login', 'Bad login data. Please check your username and password.')
  31.         case 403:
  32.           throw new Exception('software', 'This errors must not exist')
  33.         case 404:
  34.           throw new Exception('software', 'Invalid exemplar of data model')
  35.         default:
  36.           throw new Exception('software', 'Unknown error with transfering data from server.')
  37.       }
  38.     } catch (error) { throw error }
  39.   } catch (fetchError) {
  40.     throw fetchError
  41.   }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement