TypeScript Decorator to Show Toast When $axios.$get Fails in an async Method in Nuxt
/**
* Decorator for async functions
*
* When performing axios communication within a method using await $axios.$get...,
* if it fails, show an error toast.
*/
export function axiosErrorToast (_target: Vue, _propertyKey: string, descriptor: PropertyDescriptor) {
const method = descriptor.value
descriptor.value = async function (this: Vue) {
try {
return await Reflect.apply(method, this, arguments)
} catch (error) {
if (!error.isAxiosError) {
throw error
}
this.$root.$bvToast.toast('An error occurred while communicating with the server', {
title: 'Server Error',
variant: 'danger',
toaster: 'b-toaster-bottom-center'
})
}
}
}
Comments