Last active
May 1, 2020 17:25
-
-
Save jenky/fbd930dbb9c8412b3aa42119e23bc302 to your computer and use it in GitHub Desktop.
Axios interceptors with toast message using bootstrap vue
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 Vue from 'vue' | |
| export default http => { | |
| // https://github.com/mzabriskie/axios#interceptors | |
| http.interceptors.response.use( | |
| response => response, | |
| /** | |
| * This is a central point to handle all | |
| * error messages generated by HTTP | |
| * requests | |
| */ | |
| error => { | |
| const { response } = error | |
| if ([401, 419].indexOf(error.response.status) > -1) { | |
| // Reload or redirect to login page | |
| window.location.reload() | |
| return Promise.reject(error) | |
| } | |
| const errorMsg = response.data.message || response.statusText | |
| let errorDesc = null | |
| const vm = new Vue() | |
| const h = vm.$createElement | |
| if (response.status === 422) { | |
| if (response.data && response.data.errors) { | |
| errorDesc = h('div', {}, | |
| Object.values(response.data.errors).map(ms => { | |
| return h('div', {}, ms.map(m => h('div', {}, m))) | |
| }) | |
| ) | |
| } else { | |
| errorDesc = h('div', {}, response.data[0]) | |
| } | |
| } else { | |
| errorDesc = errorMsg | |
| } | |
| vm.$bvToast.toast([errorDesc], { | |
| title: errorMsg, | |
| variant: 'danger', | |
| solid: true | |
| }) | |
| return Promise.reject(error) | |
| } | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment