study

패스트캠퍼스 챌린지 43일차

swimKind 2022. 3. 7. 22:53

로그인 병렬 - 예외 처리 흐름 설계

 

로그인을 처리하는 부분에서 오류가 났을 때의 처리에 대해 추가적으로 생각해봐야 할 부분이 있다. 먼저 현재 #onSubmit 메소드 부분의 코드를 확인해 보면

 

import template from './login.template';
import TextField from '../views/text-field';
import axios  from 'axios';

export default class Login {
  #template = template;
  #data;
  #container;
  #loginFail = false;
  #fields = [];

  constructor(container, data) {
    ...
  }

  #initialize = () => {
    ...
  }

  #onSubmit = e => {
    e.preventDefault();

    const loginData = this.#fields
      .map(field => ({ [field.name]: field.value }))
      .reduce((a, b) => ({ ...a, ...b }), {});

    axios.post('/api/authentication', loginData)
      .then(result => {
        return result.data.result;
      })
      .then(({ id, token }) => {
        const options = { headers: { token } };
        this.#data.store.token = token;

        return axios.all([
          axios.get(`/api/user/${id}`, options),
          axios.get(`/api/user/${id}/posts`, options),
        ]);
      })
      .then(([profile, posts]) => {
        this.#data.store.userProfile = profile.data.result;
        this.#data.store.userPosts = posts.data.results;

        location.href = '/#/profile';
      })
      .catch(error => {      
        this.#loginFail = true;
        this.render();
      });
  }

  render = () => {
    ...
  }
}

데이터를 처리하는 부분의 Promise리턴을 3번에 걸쳐서 한다. 여기서 한번 주의해서 봐야할 점은 catch() 부분이 하나라는 것이다. 그 말은 로그인을 실패해도 하나 있는 catch() 부분에 걸리고 로그인은 성공하더라도 사용자의 정보를 받아오는 부분, axios의 데이터를 가져오는 부분에서 실패하게되도 하나의 catch()에서 걸리게 된다. 따라서, 동작이 실패가 됐을 때, 어디에서 실패를 했는지 정확하게 알 수가 없다는 것이다. 

 

이 작업에서 로그인이 실패했을 경우, 로그인이 실패했다는 정보나 데이터를 가져오는 부분에서 실패 했을 시에 데이터를 가져오는 부분에서 실패를 했다고 나타내주는 로직이 추가되면 좋을 것이다.

 

import template from './login.template';
import TextField from '../views/text-field';
import axios  from 'axios';

export default class Login {
  #template = template;
  #data;
  #container;
  #loginFail = false;
  #fields = [];

  constructor(container, data) {
    ...
  }

  #initialize = () => {
    ...
  }

  #onSubmit = e => {
    e.preventDefault();

    const loginData = this.#fields
      .map(field => ({ [field.name]: field.value }))
      .reduce((a, b) => ({ ...a, ...b }), {});

    axios.post('/api/authentication', loginData)
      .then(result => {
        return result.data.result;
      })
      .then(({ id, token }) => {
        const options = { headers: { token } };
        this.#data.store.token = token;

        axios.all([
          axios.get(`/api/user/${id}`, options),
          axios.get(`/api/user/${id}/posts`, options),
        ]).then(([profile, posts]) => {
          this.#data.store.userProfile = profile.data.result;
          this.#data.store.userPosts = posts.data.results;
  
          location.href = '/#/profile';
        }).catch(error => {      
          this.#loginFail = true;
          this.render();
        });
      })
      .catch(error => {      
        this.#loginFail = true;
        this.render();
      });
  }

  render = () => {
    ...
}

로그인 처리가 발생 했을 때 성공인지 에러인지의 처리와 데이터를 가져오는 부분에서의 성공과 에러의 처리를 나눴다. axios.all 메소드를 통해서 데이터를 불러 올때 return 하는 것이 아니라 또 다른 하나의 Promise를 반환하여 성공 시 then()을 통해 데이터를 반환하고 실패시 데이터를 불러오는 부분에서 실패하는 로직을 구현하면 두 작업을 구분해서 실행 할 수 있다.

 

 

 

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

 

#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #김민태의프론트엔드아카데미:제1강JavaScript&TypeScriptEssential