Skip to content

Instantly share code, notes, and snippets.

@sibu-github
Created January 14, 2019 14:16
Show Gist options
  • Select an option

  • Save sibu-github/b3d07304ff0a71a5c7fc0c71181dd164 to your computer and use it in GitHub Desktop.

Select an option

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
/**
* 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;
}
}
@debajyoti-thetaonelab
Copy link

debajyoti-thetaonelab commented Jan 17, 2019

All our api either returns JSON or Binary Blob
If we use fetchAPI for api's returning JSON then we can only res.json if res.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 status be passed somehow or different subclass of Error should be thrown.

We may club the response code to a fewer group like the following:

  • [50x] Code & Unknown error [ User don't need the details apart from we will be fixing it but we need to get notified ]
  • HTTP 401 Unauthorized
  • HTTP 402 Payment Required
  • HTTP 403 Forbidden
  • HTTP 404 Not Found

For each of these 40x category we may show a message showing probable cause.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment