itsource

Vue.js: Nuxt 오류 처리

mycopycode 2023. 1. 19. 07:09
반응형

Vue.js: Nuxt 오류 처리

vuex에서 오류 처리를 설정하는 데 약간의 어려움을 겪고 있습니다.적절한 에러 처리에 대해서는, 많은 방법이 있어, 문서도 거의 없는 것 같습니다.저는 4가지 대안을 실험해 보았지만, 아직 만족스러운 해결책을 찾지 못했습니다.


대안 1 - 컴포넌트 오류 검출 및 처리

페이지/패키지vue:

export default {
    methods: {
        onLogin() {
            this.$store.dispatch('auth/login', {
                email: this.email,
                password: this.password,
            }).then(() => {
                this.$router.push('/home');
            }).catch((error) {
                // handle error in component
            });
        },
    },
}

store/auth.disc:

export const actions = {
    login({ commit }, { email, password }) {
        return this.$axios.post('/api/login', {
            email,
            password,
        }).then((res) => {
            doSomething(res);
        });
    },
}

장점

  • 음.

단점

  • 오류가 처리되지 않고 vuex에 저장되었습니다.
  • 컴포넌트 방법에 많은 보일러 플레이트 코드를 도입합니다.

대안 2 - vuex에서 오류 캡처 및 처리

페이지/패키지vue:

export default {
    methods: {
        onLogin() {
            this.$store.dispatch('auth/login', {
                email: this.email,
                password: this.password,
            }).then(() => {
                this.$router.push('/home');
            });
        },
    },
}

store/auth.disc:

export const actions = {
    login({ commit }, { email, password }) {
        return this.$axios.post('/api/login', {
            email,
            password,
        }).then((res) => {
            doSomething(res);
        }).catch((error) => {
            // store error in application state
            commit('SET_ERROR', error);
        });
    },
}

장점

  • 모든 구성 요소에서 vuex를 사용하여 오류 개체에 액세스할 수 있습니다.
  • 레이아웃에 반응형 오류 구성 요소를 사용할 수 있습니다. 이 구성 요소는 오류 상태가 변경될 때 표시됩니다.

단점

  • 에러의 발생원, 어느 컴포넌트에서 에러가 발생했는지 추적할 수 있는 방법이 있는지 모르겠습니다.

대안 3 - Axios 인터셉터를 사용한 오류 캐치

plugins/sublicos.sublic:

export default function({ $axios, store }) {
    $axios.onError(error => {
        store.dispatch('setError', error);
    });
}

페이지/패키지vue:

export default {
    methods: {
        onLogin() {
            this.$store.dispatch('auth/login', {
                email: this.email,
                password: this.password,
            }).then(() => {
                this.$router.push('/home');
            });
        },
    },
}

store/auth.disc:

export const actions = {
    login({ commit }, { email, password }) {
        return this.$axios.post('/api/login', {
            email,
            password,
        }).then((res) => {
            doSomething(res);
        });
    },
}

장점

  • 글로벌 오류 처리
  • vuex 또는 컴포넌트 오류 검출 불필요
  • 보일러 플레이트 코드 없음

단점

  • 모든 예외는 처리되지 않습니다. 즉, 축 이외의 오류는 검출되지 않습니다.

대안 4 - 사용자 지정 오류 플러그인

모든 예외를 포착하는 커스텀 플러그인의 실장을 실험하고 있습니다만, 제대로 동작하지 않습니다.

plugins/module.module:

export default (ctx, inject) => {
    const catchPlugin = function (func) {
        return async function (args) {
            try {
                await func(args)
            } catch (e) {
                return console.error(e)
            }
        }
    };
    ctx.$catch = catchPlugin;
    inject('catch', catchPlugin);
}

페이지/패키지vue:

export default {
    methods: {
        onLogin: this.$catch(async function () {
            await this.$store.dispatch('auth/login', { email: this.email, password: this.password });
            this.$router.push('/home');
        }),
    },
}

장점

  • 보일러 플레이트 없음.
  • 플러그인에서 모든 오류가 발견되었습니다.

단점

  • 할 수 없어요. : (

vue/nuxt에서의 에러 처리에 관한 문서가 부족한 것 같습니다.누가 네 번째 일을 할 수 있을까?이게 이상적일까?다른 대안이 있나요?재래식이란 무엇인가?

시간 내주셔서 감사합니다!

옵션 #4가 작동하지 않는 이유는 실행되지 않는 함수를 반환하기 때문입니다.

function catchPlugin(outerFunction) {
   return function async innerFunction(args) {
     try {
       const data = await outerFunction(args);
       return { data } 
     } catch (error) {
       return { error }
     }
   }
}

사용방법:

const execute = catchPlugin((args) => {
  // do something
})

execute('myArgument');

보시다시피 예를 작동시키려면 내부 기능도 실행해야 합니다.

onLogin: this.$catch(async function () {
    await this.$store.dispatch('auth/login', { email: this.email, password: this.password });
    this.$router.push('/home');
})(), // mind the () :-)

하지만... 컴포넌트의 오류는 뷰 컴포넌트와 밀접하게 관련되어 있기 때문에 나쁜 것은 아니라고 생각합니다.예를 들어 로그인 컴포넌트에 대해 생각해 봅시다.요즘에 표시되는 것은 글로벌에러 핸들러(토스트러)입니다.이 핸들러는 사용자 이름/비밀번호가 틀리면 토스트 메시지를 표시합니다.제 경험상 이것은 최선의 동작이 아닙니다.좋은 시작점이지만, 컴포넌트 근처에 에러 메시지를 추가하여 정확히 무엇이 잘못되었는지를 표시하는 것이 좋습니다.즉, 컴포넌트 자체에 항상 오류 처리(UI 관련)를 추가해야 합니다.

우리 회사에서도 같은 제품을 취급하는 동료들과 함께 이 문제를 해결하기 위해 노력하고 있습니다.하나는 오류 처리 추가이고 다른 하나는 그렇지 않습니다.제 생각에 유일한 해결책은 개발자들이 항상 적절한 오류 처리를 추가하도록 교육하는 것입니다." " 가 붙은 async/await 않아요. '나쁜 건 아니에요'

methods: {
   async login (email, password) {
      try {
         await this.$store.dispatch('auth/login', { email, password })
         // do something after login
      } catch (error) {
         // handle error
      }
   }
}

으로 한 말씀 .con: 오류가 처리되지 않고 vuex에 저장됩니다.이게 왜 사기야?에러를 글로벌하게 사용할 수 있도록 할 필요가 있습니까?내가 많이 보는 것은 사람들이 쓸모없는 상태를 너무 많이 두는 것이다.vuex컴포넌트 자체에서만 사용됩니다.로컬 컴포넌트 상태를 갖는 것도 나쁘지 않습니다.로그인에 관한 것이므로 이 에러는 로그인 컴포넌트에서만 알 수 있습니다.

Promiseaction

vuex의 예:

NEW_AUTH({ commit }) {
    return new Promise((resolve, reject) => {
      this.$axios.$get('/token').then((res) => {
        ...
        resolve();
      }).catch((error) => {
        reject(error);
      })
    })
  }

페이지 내:

this.$store.dispatch('NEW_AUTH')
   .then(() => ... )
   .catch((error) => ... )

대안 2의 결점에 대처하려면 다음 중 하나를 수행합니다.

(a) 컴포넌트의 이름 또는 컴포넌트에 대한 참조를 전달한다.

(b) 콜을 발신한 컴포넌트의 에러 상태를 유지할 수 있습니다.그런 다음 구성 요소에서 오류가 있는지 확인하고 표시할 수 있습니다.믹스인을 사용하면 보일러 플레이트의 필요성을 없앨 수 있습니다.

store/auth.disples:

export const actions = {
    login({ commit }, { email, password }) {
        return this.$axios.post('/api/login', {
            email,
            password,
        }).then((res) => {
            doSomething(res);
            commit('save_to_state', { response: res });
        }).catch((error) => {
            commit('save_to_state', { error });
        });
    },
}

작성하다error를를누누누누다다그런 다음 특정 컴포넌트의 오류를 관련 Vuex 모듈로 디스패치합니다.그런 다음 글로벌 핸들러를 생성하여 개별 Vuex 모듈에서 오류를 감시하고 트리거된 경우 오류를 표시합니다.

// store/auth.js

export const state = () => {
  return {
    success: null,
    error: null
  }
}

export const actions = {
  async login({ commit }, { email, password }) {
    try {
      const response = await axios.post('/api/login', {
        email,
        password
      })
      commit('SET_SUCCESS', response)
    } catch(err) {
      commit('SET_ERROR', error)
    }
  }
}

export const mutations = {
  SET_SUCCESS(state, payload) {
    state.success = payload
  },
  SET_ERROR(state, payload) {
    state.error = payload
  }
}
// auth.vue

export default {
  methods: {
    onLogin() {
      try {
        await this.$store.dispatch('auth/login', {
          email: this.email,
          password: this.password
        })
        if (this.$store.state.auth.success) this.$router.push('/home')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
// app.vue

export default {
  created() {
    this.$store.subscribe((mutation, state) => {
      if (mutation.type.includes('ERROR')) {
        // display error in global error output
        console.log(mutation.payload)
      }
    })
  }
}

언급URL : https://stackoverflow.com/questions/51247371/vue-js-nuxt-error-handling

반응형