A TypeScript Decorator to Show a Toast When $axios.$get Fails in an Async Method with Nuxt
Javascriptnuxt
2020-10-07 12:49 (6 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
Related posts
If "Environment key 'es2021' is unknown" Occurs in Nuxt+Typescript
When Using Nuxt Axios Proxy Mode, Axios Config's httpsAgent Injection Cannot Handle Self-Signed Certificates on the Proxy Server
Differences in Behavior with and without Await in Functions that Create and Return Promises Inside JS Promises
How to Set Up API Proxy to Other Services in Nuxt3
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.