본문 바로가기
자바스크립트(JavaScript)

자바스크립트 @데코레이터

by BillyCho 2023. 3. 28.

@tryCatch 데코레이터를 사용하여 getData 메소드를 래핑하고, 성공하면 데이터를 반환하고 실패하면 서버의 에러 메시지를 반환하도록 하려면 다음과 같이 작성할 수 있습니다.

class TryCatchDecorator {
  static tryCatch(target, name, descriptor) {
    const original = descriptor.value;
    if (typeof original === 'function') {
      descriptor.value = async function (...args) {
        try {
          const response = await original.apply(this, args);
          return response.data;
        } catch (e) {
          console.error(`Error in ${name}:`, e);
          if (e.response && e.response.data && e.response.data.message) {
            throw new Error(e.response.data.message);
          } else {
            throw new Error(e.message);
          }
        }
      }
    }
    return descriptor;
  }
}

위 코드에서 getData 메소드를 async 함수로 변경하고, 성공하면 response.data를 반환하고, 실패하면 e.response.data.message를 반환하도록 수정했습니다. 반환된 에러는 catch 블록에서 처리할 수 있습니다.

이제 getData 메소드를 사용할 때 다음과 같이 작성할 수 있습니다.

import axios from 'axios';
import { TryCatchDecorator } from './TryCatchDecorator';

class MyComponent {
  @TryCatchDecorator.tryCatch
  async getData() {
    const response = await axios.get('/api/data');
    return response;
  }
}

const myComponent = new MyComponent();
myComponent.getData()
  .then(data => {
    console.log('Data:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

getData 메소드에서 데이터를 가져올 때 axios를 사용하고, @tryCatch 데코레이터를 사용하여 오류를 처리합니다. 반환된 데이터 또는 오류는 .then() 블록 또는 .catch() 블록에서 처리할 수 있습니다.