| Total Complexity | 8 |
| Complexity/F | 2.67 |
| Lines of Code | 46 |
| Function Count | 3 |
| Duplicated Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | import nError from './creator'; |
||
| 2 | import { isFetchResponseError, isFetchNetworkError } from './checker'; |
||
| 3 | import { CATEGORIES } from './constants'; |
||
| 4 | |||
| 5 | // parse the response error based on content-type text/html, text/plain or application/json |
||
| 6 | // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch |
||
| 7 | // https://msdn.microsoft.com/en-us/library/ms526971(v=exchg.10).aspx |
||
| 8 | export const parseFetchResponseError = async response => { |
||
| 9 | if (response.ok) { |
||
| 10 | return nError({ |
||
| 11 | category: CATEGORIES.FETCH_RESPONSE_OK, |
||
| 12 | status: response.status, |
||
| 13 | message: "it shouldn't be caught as exception, please check the code", |
||
| 14 | }); |
||
| 15 | } |
||
| 16 | |||
| 17 | const { status, headers } = response; |
||
| 18 | const contentType = headers.get('content-type'); |
||
| 19 | const parseMethod = |
||
| 20 | contentType && contentType.includes('application/json') ? 'json' : 'text'; |
||
| 21 | const message = await response[parseMethod](); // system Error would be thrown if it fails |
||
| 22 | return nError({ |
||
| 23 | category: CATEGORIES.FETCH_RESPONSE_ERROR, |
||
| 24 | status, |
||
| 25 | message, |
||
| 26 | contentType, |
||
| 27 | }); |
||
| 28 | }; |
||
| 29 | |||
| 30 | export const parseFetchNetworkError = e => |
||
| 31 | nError({ |
||
| 32 | category: CATEGORIES.FETCH_NETWORK_ERROR, |
||
| 33 | message: e.message, |
||
| 34 | code: e.code, |
||
| 35 | }); |
||
| 36 | |||
| 37 | export const parseFetchError = async e => { |
||
| 38 | if (isFetchResponseError(e)) { |
||
| 39 | const parsedError = await parseFetchResponseError(e); |
||
| 40 | return parsedError; |
||
| 41 | } |
||
| 42 | if (isFetchNetworkError(e)) { |
||
| 43 | return parseFetchNetworkError(e); |
||
| 44 | } |
||
| 45 | return e; // uncaught exception |
||
| 46 | }; |
||
| 47 |