File size: 2,343 Bytes
4327358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { ApiError } from '@figuro/chatwoot-sdk/dist/core/ApiError';
import { AxiosError } from 'axios';

/**
 * Class responsible for rendering error information based on error type
 */
export class ErrorRenderer {
  /**
   * Renders error information based on error type
   * @param error The error to render
   * @returns Formatted error text
   */
  public renderError(error: any): string {
    // Handle Axios errors
    if (error.isAxiosError) {
      return this.renderAxiosError(error as AxiosError);
    }

    // Handle Chatwoot SDK ApiError
    if (error instanceof ApiError) {
      return this.renderApiError(error);
    }

    // For all other errors
    return this.renderGenericError(error);
  }

  /**
   * Renders Axios error information
   * @param error The Axios error to render
   * @returns Formatted error text
   */
  private renderAxiosError(error: AxiosError): string {
    let errorText = `Axios Error: ${error.message}`;
    if (!error.response?.data) {
      return errorText;
    }

    // Add response data if it exists and is JSON
    try {
      const data = error.response.data as any;
      let json: undefined;
      if (Buffer.isBuffer(data)) {
        json = JSON.parse(data.toString());
      } else if (typeof data === 'object') {
        json = data;
      } else {
        json = JSON.parse(data as any);
      }
      errorText += `\nData: ${JSON.stringify(json, null, 2)}`;
    } catch (e) {
      errorText += 'Data: <unparsable>';
    }

    return errorText;
  }

  /**
   * Renders Chatwoot SDK ApiError information
   * @param error The ApiError to render
   * @returns Formatted error text
   */
  private renderApiError(error: ApiError): string {
    let errorText = `API Error: ${error.message}`;
    errorText += `\nStatus: ${error.status}`;

    // Add body if it exists
    if (error.body) {
      try {
        const body =
          typeof error.body === 'object' ? error.body : JSON.parse(error.body);
        errorText += `\nBody: ${JSON.stringify(body, null, 2)}`;
      } catch (e) {
        errorText += `\nBody: ${error.body}`;
      }
    }

    return errorText;
  }

  /**
   * Renders generic error information
   * @param error The error to render
   * @returns Formatted error text
   */
  private renderGenericError(error: any): string {
    return error.toString();
  }
}