Skip to content

Instantly share code, notes, and snippets.

@mrchimp
Created July 16, 2021 17:11
Show Gist options
  • Select an option

  • Save mrchimp/9b8557cf1b21514e53505517b03c7292 to your computer and use it in GitHub Desktop.

Select an option

Save mrchimp/9b8557cf1b21514e53505517b03c7292 to your computer and use it in GitHub Desktop.
XHR Error Handler Vue Mixin
axios.post("/api/route")
.then(response => {
// It worked
})
.catch(handleAxiosValidationErrors)
.catch(e => {
// A non-422 error happened.
})
.then(e => {
// If a 422 happened it will be passed here. Otherwise e will be undefined.
})
const request = new Request("/api/thing", { method: "POST" });
fetch(request)
.then(this.handleFetchValidationErrors)
.catch(e => {
// A non-422 error happened.
})
.then(e => {
// If a 422 happened it will be passed here. Otherwise e will be undefined.
});
import get from "lodash/get";
export default {
data() {
return {
xhrErrors: [],
xhrMessage: null
};
},
methods: {
resetXhrErrors() {
(this.xhrErrors = []), (this.xhrMessage = null);
},
handleAxiosValidationErrors(e) {
return new Promise((resolve, reject) => {
if (e.response.status === 422) {
this.xhrErrors = e.response.data.errors;
this.xhrMessage = e.response.data.message;
resolve(e);
} else {
reject(e);
}
});
},
handleFetchValidationErrors(response) {
return new Promise((resolve, reject) => {
console.log("status", response.status);
if (response.status === 422) {
response.json().then(data => {
this.xhrErrors = data.errors;
this.xhrMessage = data.message;
resolve(response);
});
} else {
reject(response);
}
});
},
getErrors(name) {
return get(this.xhrErrors, name, []);
},
hasErrors(name) {
return !!get(this.xhrErrors, name, []);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment