Vuex 및 Axios를 사용한 Vuej에서의 오류 처리의 베스트 프랙티스
Vuex + axios를 사용하고 있는데 vuex + axios 오류 처리의 베스트 프랙티스를 알고 싶습니다.제가 지금 하고 있는 것은 악시를 사용하여 요청했을 때 오류가 반환되면 변환되어 상태가 갱신되는 것입니다.제가 원하는 것은 제 요청에서 응답 오류가 발생하면 제 컴포넌트로 돌아가기 때문에 훨씬 더 빨리 오류를 처리할 수 있다는 것입니다.
각도처럼 의존성 주입이 있고 반응이 성분으로 돌아갑니다.
케이크도 먹고 드세요.이미 요격기를 사용하고 있다고 가정하면...
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
store.commit('ERROR', error) // just taking some guesses here
return Promise.reject(error) // this is the important part
})
이렇게 하면 약속 거부가 발신자에게 돌아가기 때문에 컴포넌트에서는...
axios.whatever(...).then(res => {
// happy days
}, err => {
// oh noes!
})
그냥 캐치볼을 사용해요.내가 vuex로 바꾸기 전에 사용하던 것과 똑같아.이 솔루션은 아마도 가장 보편적이고 문서화된 솔루션일 것입니다.또한 이전과 마찬가지로 컴포넌트의 HTML에 오류를 삽입할 수 있습니다.또한 로딩 = true, 로딩 = false html 애니메이션을 계속 사용할 수 있습니다.
따라서 데이터, 오류 및 로딩의 3가지 상태 속성이 표시됩니다.나한테는 효과가 있는 것 같아.마일리지가 다를 수 있습니다.vuex 모듈과 네임스페이스도 사용하고 있습니다만, 이것이 없는 간단한 예를 다음에 나타냅니다.
//somevuexstore.js
actions: {
fetchData(context) {
axios
.get("api/someendpoint")
.then(response => {
context.commit('loading')
context.commit('organizations', response.data)
}).catch(error => {
console.log(error.response.data.message || error.message)
context.commit('error', error)
});
},
mutations: {
organizations(state, data) {
return state.organization = data
},
error(state, data) {
return state.error = data
},
loading(state) {
return state.loading = false
},
state= {
organization: [],
error: '',
loading: true
}
그리고 내 컴포넌트에.지금까지의 방법과 매우 비슷하지만 추가된 계산 속성만 있습니다.
computed: {
...mapState({
getError: 'error',
getLoading: 'loading',
getAllOrg: 'organization',
}),
}
mounted() {
this.$store.dispatch('fetchData')
}
그리고 내 html은 이런 것들이야.
<tr v-for="value in getAllOrg" :key="value.id">
<td>{{ value.id }}</td>
<td>{{ value.email }}</td>
<td>{{ value.name }}</td>
<td>{{ value.['created-at'] | formatDate }}</td>
</tr>
필요에 따라 오류 메시지를 삽입합니다.
<div v-if="getError" class="error">
<p>{{ getError }}</p>
</div>
애니메이션을 로드하기 위해 적절한 경우 html에 삽입된 vue spinners 패키지를 사용합니다.
<div v-if="getLoading" style="height:37px;">
<p>
<bar-loader class="custom-class" color="#c2c2c2"
getLoading="getLoading"
:width="130"></bar-loader>
</p>
접근법에 대해 알려드리겠습니다. 오류 로깅에 사용한 내용은 다음과 같습니다.이것에 의해, 온 코드로 모든 vue 에러를 처리할 수 있습니다.
window.onerror = function (message, source, lineno, colno, error) {
/// what you want to do with error here
};
이것은 브라우저의 글로벌오류 핸들러입니다검출되지 않은 에러가 발생했을 경우는, 이것으로 처리할 수 있습니다.
또한, 당신의 오류를 처리하고 싶다면.당신은 이걸 할 수 있다.
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
// when you throw error this will also fetch error.
throw error;
});
vue에서 오류 처리를 확인하려면 다음 절차를 수행합니다.https://vuejs.org/v2/api/ #error 핸들러
Vue.config.errorHandler = function (err, vm, info) {
// handle error
// `info` is a Vue-specific error info, e.g. which lifecycle hook
// the error was found in. Only available in 2.2.0+
}
window.onerror가 사용되는 링크를 제공합니다.
https://github.com/stacktracejs/stacktrace.js/
이렇게 이벤트 버스를 이용할 수 있습니다.
import Vue from 'vue'
export const EventBus = new Vue();
다음으로 에러를 트리거합니다.
axios.get(...)
.catch(function (error) {
EventBus.$emit('error', error)
});
에러 처리의 일반적인 방법이 항상 존재하는 것은 아니기 때문에, 어떻게든 콘텍스트에 관련지을 필요가 있다는 결론에 도달했습니다.api 파일이 따로 있는 것은 좋지만, 위의 내용으로 조정해 주세요.저는 별도의 API 파일을 가지고 있으며 다음 작업을 하고 있습니다.
//comments-api.js
export default {
get (url, handler){
//return the promise to further possible chains
return axios.get(url)
.then( response => handler.success(response.data) )
.catch( error => handler.serverDownOrUnexpected(error.response) )
},
}
//comments.js - vuex module
import $comments from './../../services/api/comments-api'
...
actions: {
$comments.get(url, {
success: (data) => commit('success_handler', data),
serverDownOrUnexpected: (error) => commit('unexpected', error)
//so on...
})
}
...
이 접근법에서는 특정 에러 처리 방법을 변경하고 싶을 때마다 한 곳에서 변경을 가해야 합니다.또, 디커플링 된 코드의 메리트가 있습니다.
약속의 힘! (그리고 비동기/대기)
vue 메서드(mycomponent.mycomponent)
async YourAsyncMethod() {
const payload = {key: "var"}
const result = await axios
.post('/your/api/endpoint', payload)
.catch(e => {
console.log(e.message)
});
}
yourMethod() {
// start axios logic
const payload = {key: "var"}
axios
.post('/your/api/endpoint', payload)
.then(response => {
console.log(response.data)
// start state action logic
this.$store
.dispatch('yourAction', payload)
.then(add => {
console.log('success mutation!');
})
.catch(error => {
// error = Error object,
console.log('error mutation:',error.message);
console.log(error) // to se full error object
});
})
.catch(error => {
console.log('error axios request', error.data)
});
}
스테이트 액션(store/actions.displays)을 사용합니다.
yourAction(){
const some_logic = false;
if (!some_logic) {
// when return a Promisse.reject
//you can get error with catch(e) from youtMethod
return Promise.reject(new Error("Impressora já adicionada"))
}
context.commit('MUTATION_METHOD', payload);
}
공리적으로
http
.post('/your/api/endpoint', payload)
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log('error', error.data)
});
Vuex에 "마지막 로드" 상태를 추가하고 루트의 변화를 확인합니다.
무겁고 복잡해 보이지만 논리적이고 컴포넌트를 잘 분리할 수 있습니다.
보너스: 데이터를 로드하고 시도가 성공했는지 즉시 알 수 있습니다.
VUE 3 구성 API에서 고유하게 사용 가능
AX를 사용할 수 있습니다.IOS 인터셉터: 원하는 설정을 설정하기 위한 매뉴얼로 VUE에서 사용
import {onErrorCaptured, ref} from "vue";
setup(){
let errors = ref(null)
onErrorCaptured((error)=>{
// checking for server response first
errors.value = error.response?Object.values(error.response.data)[0]:error.message
})
return{errors}
}
언급URL : https://stackoverflow.com/questions/48656993/best-practice-in-error-handling-in-vuejs-with-vuex-and-axios
'programing' 카테고리의 다른 글
Vue 라우터는 초기 로딩 시 항상 느리게 로드된 모듈을 로드합니다. (0) | 2022.07.17 |
---|---|
비정상적인 리다이렉트 (0) | 2022.07.17 |
Valgrind에 의해 아직 도달 가능한 누출이 감지됨 (0) | 2022.07.17 |
왜 사용 포인터 대신 배열 크기 1? (0) | 2022.07.17 |
Java Streams가 일회성인 이유는 무엇입니까? (0) | 2022.07.13 |