Skip to content

Instantly share code, notes, and snippets.

@moreta
Created January 18, 2019 09:53
Show Gist options
  • Save moreta/a47cb349c308610d6075bb31dce8bb87 to your computer and use it in GitHub Desktop.
Save moreta/a47cb349c308610d6075bb31dce8bb87 to your computer and use it in GitHub Desktop.
vue fetch error handling with event bug
<template>
<transition enter-active-class="animated fadeIn">
<router-view></router-view>
</transition>
</template>
<script>
import notifyError from 'path/utils/common/notifyError'
import { MessageBox } from 'element-ui'
import EventBus from 'path/event-bus'
export default {
mounted () {
EventBus.$on('onNotify', err => {
notifyError(err)
})
EventBus.$on('onError', err => {
console.error(err)
let msg = err
if (err.messages) {
msg = err.messages
} else if (err.message) {
msg = err.message
} else if (err.response && err.response.data && err.response.data.messages) {
msg = err.response.data.messages
}
let message = msg
if (msg instanceof Array) {
let h = this.$createElement
const msgList = msg.map((m) => {
return h('li', null, m)
})
message = h('ul', msgList)
}
notifyError(err) // bugsnag notify
MessageBox({
title: 'エラーが発生しました',
closeOnClickModal: false,
message: message
})
})
}
}
</script>
// https://alligator.io/vuejs/global-event-bus/
import Vue from 'vue'
const EventBus = new Vue()
export default EventBus
import EventBus from 'path/event-bus'
const state = {
fetching: false
}
const actions = {
startFetch: ({ commit }) => {
return new Promise((resolve, reject) => {
commit('startFetch')
resolve()
})
},
fetching: ({ dispatch, commit }, fetching) => {
dispatch('startFetch')
.then(fetching)
.then(() => {
commit('endFetch')
})
.catch(err => {
commit('endFetch')
EventBus.$emit('onError', err)
})
}
}
const mutations = {
startFetch (state) {
state.fetching = true
},
endFetch (state) {
state.fetching = false
}
}
export default {
state,
actions,
mutations
}
<template>
</template>
<script>
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'fetching',
'sampleAction'
]),
handleUpdate (param) {
this.fetching(() => {
return this.sampleAction(param)
})
}
}
}
</script>
@moreta
Copy link
Author

moreta commented Jan 18, 2019

fetchでcatchして、handlingしないエラーは全部 dialogに出す。

dialogはelement uiのMessageBoxを使った例だけどdialogは好みで変更すれば大丈夫

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