A TypeScript Decorator to Show a Toast When $axios.$get Fails in an Async Method with Nuxt

Javascript nuxt
2020-10-07 21:49 (4 years ago) ytyng

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'
})
}
}
}
Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011