Skip to content

Instantly share code, notes, and snippets.

View rob-long's full-sized avatar
🎯
Focusing

Rob Long rob-long

🎯
Focusing
View GitHub Profile
@odewahn
odewahn / error-handling-with-fetch.md
Last active June 9, 2024 14:27
Processing errors with Fetch API

I really liked @tjvantoll article Handling Failed HTTP Responses With fetch(). The one thing I found annoying with it, though, is that response.statusText always returns the generic error message associated with the error code. Most APIs, however, will generally return some kind of useful, more human friendly message in the body.

Here's a modification that will capture this message. The key is that rather than throwing an error, you just throw the response and then process it in the catch block to extract the message in the body:

fetch("/api/foo")
  .then( response => {
    if (!response.ok) { throw response }
    return response.json()  //we only get here if there is no error
 })
@jpadilla
jpadilla / components.my-component.js
Last active September 5, 2018 19:07
ember-concurrency-demo
import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';
export default Ember.Component.extend({
task: Ember.computed('query', function() {
return this.get('fetchData').perform(this.query);
}),
fetchData: task(function*(query) {
yield timeout(3000);
@nagarajanpp8
nagarajanpp8 / controllers.application.js
Created March 7, 2019 13:13
model-hook-without-blocking-ui-using-ember-concurrency
import Ember from 'ember';
export default Ember.Controller.extend({
appName: ''
});
@DouglasdeMoura
DouglasdeMoura / api.ts
Last active July 21, 2024 18:14
Tiny wrapper around fetch
// Extends the return of the HTTPError class
class HTTPError extends Error {
readonly response: any;
readonly status: number;
readonly statusText: string;
constructor(status: number, statusText: string, response: any) {
super(statusText);
this.status = status;
this.statusText = statusText;