Created
July 16, 2021 17:11
-
-
Save mrchimp/9b8557cf1b21514e53505517b03c7292 to your computer and use it in GitHub Desktop.
XHR Error Handler Vue Mixin
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
| 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. | |
| }) |
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
| 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. | |
| }); |
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
| 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