feat: error response interceptor

This commit is contained in:
Methapon2001 2023-11-30 15:36:03 +07:00
parent a27dda4300
commit 3a310ef9db
No known key found for this signature in database
GPG key ID: 849924FEF46BD132
3 changed files with 88 additions and 0 deletions

View file

@ -0,0 +1,39 @@
<script setup lang="ts">
import { watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useErrorStore } from '@/stores/error'
import { useLoader } from '@/stores/loader'
const { visible, title, msg } = storeToRefs(useErrorStore())
const loader = useLoader()
watch(visible, () => {
loader.hide()
})
</script>
<template>
<q-dialog transition-show="scale" transition-hide="scale" v-model="visible">
<q-card style="width: 400px">
<q-card-section>
<span class="text-h6">
<q-icon name="error" color="negative" size="2.5rem" />{{
title
}}</span
>
</q-card-section>
<q-card-section class="q-pt-none">{{ msg }}</q-card-section>
<q-card-actions align="right" class="bg-white text-primary">
<q-space />
<q-btn
flat
v-close-popup
label="ปิด"
@click="() => (visible = !visible)"
/>
</q-card-actions>
</q-card>
</q-dialog>
</template>

View file

@ -1,5 +1,8 @@
import axios from 'axios'
import { getToken } from './KeyCloakService'
import { useErrorStore } from '@/stores/error'
const error = useErrorStore()
const instance = axios.create()
@ -8,4 +11,22 @@ instance.interceptors.request.use(async (config) => {
return config
})
instance.interceptors.response.use(
(res) => res,
(err) => {
const status = err.response.status
const data = err.response.data
error.title = 'เกิดข้อผิดพลาด'
if (status === 500) {
error.msg = 'เกิดข้อผิดพลาด ไม่สามารถดำเนินการต่อได้ กรุณาลองใหม่อีกครั้ง'
} else {
error.msg = data.message
}
error.show()
},
)
export default instance

View file

@ -0,0 +1,28 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useErrorStore = defineStore('error-data', () => {
const visible = ref<boolean>(false)
const title = ref<string>('')
const msg = ref<string>('')
function set(obj: { title: string; msg: string }, timeout?: number) {
title.value = obj.title
msg.value = obj.msg
show(timeout)
}
function show(timeout: number = -1) {
visible.value = true
if (timeout > 0) {
setTimeout(() => (visible.value = false), timeout)
}
}
function hide() {
visible.value = false
}
return { visible, title, msg, show, hide, set }
})