1 | import { AppError, _isErrorObject } from '@naturalcycles/js-lib'
|
2 | import { inspect, InspectOptions } from 'util'
|
3 |
|
4 | export interface InspectAnyOptions extends InspectOptions {
|
5 | |
6 |
|
7 |
|
8 | maxLen?: number
|
9 |
|
10 | |
11 |
|
12 |
|
13 |
|
14 | noErrorStack?: boolean
|
15 | }
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | export function inspectAny(obj: any, opt: InspectAnyOptions = {}): string {
|
33 | let s: string
|
34 |
|
35 | if (obj instanceof Error) {
|
36 |
|
37 | s = (!opt.noErrorStack && obj.stack) || [obj?.name, obj.message].filter(Boolean).join(': ')
|
38 |
|
39 | if (obj instanceof AppError) {
|
40 | s = [s, Object.keys(obj.data).length > 0 && inspectAny(obj.data, opt)]
|
41 | .filter(Boolean)
|
42 | .join('\n')
|
43 | } else if (typeof (obj as any).code === 'string') {
|
44 | s = (obj as any).code + '\n' + s
|
45 | }
|
46 | } else if (_isErrorObject(obj)) {
|
47 | s = [obj.message, Object.keys(obj.data).length > 0 && inspectAny(obj.data, opt)]
|
48 | .filter(Boolean)
|
49 | .join('\n')
|
50 | } else if (typeof obj === 'string') {
|
51 | s = obj.trim() || 'empty_string'
|
52 | } else {
|
53 | s = inspect(obj, {
|
54 | breakLength: 80,
|
55 | depth: 6,
|
56 | ...opt,
|
57 | })
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 | if (opt.maxLen && s.length > opt.maxLen) {
|
63 | s = s.slice(0, opt.maxLen) + `... ${Math.ceil(s.length / 1024)} KB message truncated`
|
64 | }
|
65 |
|
66 | return s
|
67 | }
|