에러 관련 propery
- message
- name
- stack
- statusCode
커스텀 에러
- Erorr 클래스를
상속받아
커스텀 에러 클래스를 만들게 되면 obj instanceof Error
를 사용해서 에러 객체를 식별할 수 있다는 장점이 생김
에러 확장
AxiosError 클래스 상속받기
class CustomAxiosError extends AxiosError {
constructor(message, config, code, request, response) {
super(message, config, code, request, response);
this.name = 'CustomAxiosError';
this.customProperty = 'customValue';
}
}
import axios, { AxiosError } from 'axios';
class CustomAxiosError implements AxiosError {
name: string;
message: string;
config: object;
code?: string | null;
request?: any;
response?: object;
constructor(message: string, config: object, code?: string, request?: any, response?: object) {
this.name = 'CustomAxiosError';
this.message = message;
this.config = config;
this.code = code;
this.request = request;
this.response = response;
}
logError() {
console.error(`Custom Axios error: ${this.message}`);
}
}
axios.get('/api/data')
.then(response => {
console.log(response.data);
})
.catch((error: CustomAxiosError) => {
error.logError();
});
import axios, { AxiosResponse, AxiosError } from 'axios';
class MyCustomError extends Error {
constructor(message: string) {
super(message);
this.name = 'MyCustomError';
}
}
const api = axios.create({
baseURL: 'https://api.example.com',
});
api.interceptors.response.use(
(response: AxiosResponse) => {
console.log(`Response status: ${response.status}`);
return response;
},
(error: AxiosError) => {
const customError = new MyCustomError('Request failed');
if (error.response) {
console.error(`Request failed with status ${error.response.status}`);
customError.message = `Request failed with status ${error.response.status}`;
} else if (error.request) {
console.error('No response received');
customError.message = 'No response received';
Reference