@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() 블록에서 처리할 수 있습니다.
'자바스크립트(JavaScript)' 카테고리의 다른 글
JSON Web Token (JWT) 이해하기 (0) | 2025.02.09 |
---|---|
[리액트] 카카오 로그인 기능 구하기 (0) | 2022.12.17 |
[자바스크립트] slice() (0) | 2022.12.07 |
[자바스크립트] 개방 폐쇄 원칙 SOLID : Open-Closed Principle (0) | 2022.12.04 |
자바스크립트 프라미스 all(), race(), allSettled() and any() (0) | 2022.11.21 |