A TypeScript Decorator to Show a Toast When $axios.$get Fails in an Async Method with Nuxt
Javascriptnuxt
2020-10-07 12:49 (5 years ago)

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'
})
}
}
}
Please rate this article (No signup or login required)
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.