Created
January 14, 2019 14:16
-
-
Save sibu-github/b3d07304ff0a71a5c7fc0c71181dd164 to your computer and use it in GitHub Desktop.
A common function which can handle all fetch calls with proper error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Common fetchAPI which can handle GET and POST method | |
| * Content-Type is set to 'application/json' | |
| * payload should be in JSON format | |
| */ | |
| export async function fetchAPI(url, data, method = 'POST') { | |
| // raise an error if url is missig | |
| if (!url) { | |
| throw new Error('url is missing'); | |
| } | |
| // allow only POST or GET | |
| if (method !== 'POST' || method !== 'GET') { | |
| throw new Error('Only POST and GET is allowed'); | |
| } | |
| // when method is POST the data is required | |
| // a blank object like `{}` can be passed | |
| // when there is no need for an request body | |
| // NOTE: making data parameter as required | |
| // becasue JSON.stringify could act weirdly in some cases | |
| if (method === 'POST' && !data) { | |
| throw new Error('data is required for POST'); | |
| } | |
| // data can either be an object or an array for POST | |
| if (method === 'POST' && !Array.isArray(data) && typeof data !== 'object') { | |
| throw new Error('data is required for POST'); | |
| } | |
| // build the request payload | |
| const payload = {}; | |
| payload.credentials = 'include'; | |
| payload.headers = { 'Content-Type': 'application/json' }; | |
| // body should not present when the request method is GET | |
| if (method === 'POST') { | |
| payload.body = JSON.stringify(data); | |
| } | |
| try { | |
| const res = await fetch(url, payload); | |
| const json = await res.json(); | |
| if (res.ok) { | |
| // all ok the return the data which will resolve the promise | |
| return json; | |
| } | |
| // if res.ok is not truthy then there is some API error, | |
| // throw an error which will reject the promise | |
| const { status } = res; | |
| throw new Error( | |
| `API Error: Response Status ${status} \n${JSON.stringify(json)}` | |
| ); | |
| } catch (err) { | |
| // throw any other error caught in this function | |
| throw err; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
All our api either returns JSON or Binary Blob
If we use fetchAPI for api's returning JSON then we can only
res.jsonifres.ok === true.Otherwise response can be nginx's html error page.
Response code *401, 402, 403, 404 * or maybe of interest to application/user. So either the
statusbe passed somehow or different subclass ofErrorshould be thrown.We may club the response code to a fewer group like the following:
For each of these 40x category we may show a message showing probable cause.