JavaScript 에러 클래스 커스텀

정은경·2023년 3월 30일
0

👸 Front-End Queen

목록 보기
252/278

에러 관련 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;
  }

  // Add custom error handling methods as needed
  logError() {
    console.error(`Custom Axios error: ${this.message}`);
  }
}

// Use custom Axios error class to make requests in your components
axios.get('/api/data')
  .then(response => {
    console.log(response.data);
  })
  .catch((error: CustomAxiosError) => {
    error.logError(); // Call custom error handling method
  });
import axios, { AxiosResponse, AxiosError } from 'axios';

// Custom error class
class MyCustomError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'MyCustomError';
  }
}

// Create an Axios instance
const api = axios.create({
  baseURL: 'https://api.example.com',
});

// Add response interceptor
api.interceptors.response.use(
  // Modify response data before passing it to the then() callback
  (response: AxiosResponse) => {
    // Do something with response data
    console.log(`Response status: ${response.status}`);
    return response;
  },
  // Handle errors
  (error: AxiosError) => {
    // Create custom error object
    const customError = new MyCustomError('Request failed');
    
    if (error.response) {
      // Handle response errors
      console.error(`Request failed with status ${error.response.status}`);
      customError.message = `Request failed with status ${error.response.status}`;
    } else if (error.request) {
      // Handle network errors
      console.error('No response received');
      customError.message = 'No response received';

Reference

profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글