Skip to content

Instantly share code, notes, and snippets.

@victorwpbastos
Created June 6, 2019 15:23
Show Gist options
  • Save victorwpbastos/56c323515be691ef9290713bbf72ec3b to your computer and use it in GitHub Desktop.
Save victorwpbastos/56c323515be691ef9290713bbf72ec3b to your computer and use it in GitHub Desktop.
Vue error handler component
import Vue from 'vue';
import {
VDialog,
VCard,
VCardText,
VToolbar,
VToolbarTitle,
VSpacer,
VIcon,
VExpansionPanel,
VExpansionPanelContent
} from 'vuetify/lib';
export default function useErrorHandler(fn, { timeout = 0 }) {
let errorView = new Vue({
components: {
VDialog,
VCard,
VCardText,
VToolbar,
VToolbarTitle,
VSpacer,
VIcon,
VExpansionPanel,
VExpansionPanelContent
},
data() {
return {
message: 'Erro',
errorMessage: '',
errorData: [],
entered: false,
shouldClose: false
};
},
render: function(h) {
return h(
'v-dialog',
{
props: {
value: true,
persistent: true,
scrollable: true,
maxWidth: 600,
contentClass: 'error-dialog'
}
},
[
h('v-card', [
h(
'v-toolbar',
{
props: {
flat: true,
dark: true,
dense: true,
color: 'red darken-1'
}
},
[
h(
'v-toolbar-title',
{
style: {
'margin-left': '-8px'
}
},
this.message
),
h('v-spacer'),
h(
'v-icon',
{
style: {
'margin-right': '-12px'
},
on: {
click: this.close
}
},
'close'
)
]
),
h('v-card-text', [
h(
'div',
{
class: {
'pb-3': this.errorMessage !== ''
}
},
this.errorMessage
),
h('v-expansion-panel', [
h(
'v-expansion-panel-content',
{
style: {
background: '#FFF9C4'
}
},
[
h(
'template',
{
slot: 'header'
},
[h('strong', 'Detalhes do erro')]
),
h(
'div',
{
class: ['px-3', 'pb-3']
},
[h('pre', this.errorData)]
)
]
)
])
])
])
]
);
},
methods: {
close() {
this.$destroy();
}
},
mounted() {
document.body.appendChild(this.$el);
let el = document.querySelector('.error-dialog');
el.addEventListener('mouseenter', e => {
this.entered = true;
});
el.addEventListener('mouseleave', e => {
this.entered = false;
if (this.shouldClose) {
this.close();
}
});
if (timeout > 0) {
setTimeout(() => {
if (!this.entered) {
this.close();
} else {
this.shouldClose = true;
}
}, timeout);
}
},
beforeDestroy() {
document.body.removeChild(this.$el);
}
});
function handleError(error) {
if (error) {
if (error.message) {
errorView.message = error.message;
}
if (error.errorMessage) {
errorView.errorMessage = error.errorMessage;
}
if (error.errorData) {
errorView.errorData = JSON.stringify(error.errorData, null, 4);
} else {
errorView.errorData = JSON.stringify(error.toString(), null, 4);
}
}
errorView.$mount();
}
try {
return fn().catch(handleError);
} catch (error) {
if (error.message !== "Cannot read property 'catch' of undefined") {
handleError(error);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment