• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

homer0 / packages / 4422859008

pending completion
4422859008

push

github

homer0
fix(eslint-plugin): use project as an array in the preset

720 of 720 branches covered (100.0%)

Branch coverage included in aggregate %.

2027 of 2027 relevant lines covered (100.0%)

45.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

100.0
/packages/public/error-handler/src/index.ts
1
import { simpleLogger, type SimpleLogger } from '@homer0/simple-logger';
1✔
2
import { providerCreator, injectHelper } from '@homer0/jimple';
1✔
3
/**
4
 * The dictionary of dependencies that need to be injected in {@link ErrorHandler}.
5
 */
6
type ErrorHandlerInjectOptions = {
7
  /**
8
   * The service that logs the messages on the console.
9
   */
10
  simpleLogger: SimpleLogger;
11
  /**
12
   * An alternative to the regular logger, with the project name.
13
   */
14
  appLogger: SimpleLogger;
15
};
16
/**
17
 * The inject helper to resolve the dependencies.
18
 */
19
const deps = injectHelper<ErrorHandlerInjectOptions>();
1✔
20
/**
21
 * The options for the service constructor.
22
 */
23
export type ErrorHandlerOptions = {
24
  /**
25
   * A dictionary with the dependency injections for the service. If one or more are not
26
   * provided, the service will create new instances.
27
   */
28
  inject?: Partial<ErrorHandlerInjectOptions>;
29
  /**
30
   * Whether or not to exit the process after receiving an error.
31
   *
32
   * @default true
33
   */
34
  exitOnError?: boolean;
35
};
36
/**
37
 * A small service that reads the contents of the implementation's package.json file.
38
 */
39
export class ErrorHandler {
1✔
40
  /**
41
   * Used to log the errors on the console.
42
   */
43
  protected logger: SimpleLogger;
12✔
44
  /**
45
   * Whether or not to exit the process after receiving an error.
46
   */
47
  readonly exitOnError: boolean;
12✔
48
  /**
49
   * The list of events this handler will listen for in order to catch errors.
50
   */
51
  protected eventNames: string[] = ['uncaughtException', 'unhandledRejection'];
12✔
52
  constructor({ inject = {}, exitOnError = true }: ErrorHandlerOptions = {}) {
19✔
53
    this.logger = deps.get(inject, 'simpleLogger', () => simpleLogger());
12✔
54
    this.exitOnError = exitOnError;
12✔
55
    this.handle = this.handle.bind(this);
12✔
56
    this.stopListening = this.stopListening.bind(this);
12✔
57
  }
58
  /**
59
   * Starts listening for unhandled errors.
60
   *
61
   * @returns A function to stop listing (a reference for
62
   *          {@link ErrorHandler.stopListening}).
63
   */
64
  listen() {
65
    this.eventNames.forEach((eventName) => {
2✔
66
      process.on(eventName, this.handle);
4✔
67
    });
68

69
    return this.stopListening;
2✔
70
  }
71
  /**
72
   * Stops listening for unhandled errors.
73
   */
74
  stopListening() {
75
    this.eventNames.forEach((eventName) => {
1✔
76
      process.removeListener(eventName, this.handle);
2✔
77
    });
78
  }
79
  /**
80
   * This is called by the process listeners when an uncaught exception is thrown or a
81
   * rejected promise is not handled. It logs the error on detail.
82
   * The process exits when after logging an error.
83
   *
84
   * @param error  The unhandled error.
85
   */
86
  handle(error: Error) {
87
    // If the logger is configured to show the time...
88
    if (this.logger.showTime) {
3✔
89
      // ...just send the error.
90
      this.logger.error(error);
2✔
91
    } else {
92
      // ...otherwise, get the time on a readable format.
93
      const time = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
1✔
94
      // Build the error message with the time.
95
      const message = `[${time}] ${error.message}`;
1✔
96
      // Log the new message with the exception.
97
      this.logger.error(message, error);
1✔
98
    }
99

100
    // Check if it should exit the process.
101
    if (this.exitOnError) {
3✔
102
      // eslint-disable-next-line no-process-exit
103
      process.exit(1);
2✔
104
    }
105
  }
106
}
107
/**
108
 * Shorthand for `new ErrorHandler()`.
109
 *
110
 * @param args  The same parameters as the {@link ErrorHandler} constructor.
111
 * @returns A new instance of {@link ErrorHandler}.
112
 */
113
export const errorHandler = (
1✔
114
  ...args: ConstructorParameters<typeof ErrorHandler>
115
): ErrorHandler => new ErrorHandler(...args);
1✔
116

117
/**
118
 * The options for the {@link ErrorHandler} Jimple's provider creator.
119
 */
120
export type ErrorHandlerProviderOptions = Omit<ErrorHandlerOptions, 'inject'> & {
121
  /**
122
   * The name that will be used to register the service.
123
   *
124
   * @default 'errorHandler'
125
   */
126
  serviceName?: string;
127
  /**
128
   * A dictionary with the name of the services to inject. If one or more are not
129
   * provided, the service will create new instances.
130
   */
131
  services?: {
132
    [key in keyof ErrorHandlerInjectOptions]?: string;
133
  };
134
};
135
/**
136
 * A provider creator to register {@link ErrorHandler} in a Jimple container.
137
 */
138
export const errorHandlerProvider = providerCreator(
1✔
139
  ({ serviceName = 'errorHandler', ...rest }: ErrorHandlerProviderOptions = {}) =>
4✔
140
    (container) => {
4✔
141
      container.set(serviceName, () => {
4✔
142
        const { services = {}, ...options } = rest;
4✔
143
        const inject = deps.resolve(['simpleLogger', 'appLogger'], container, services);
4✔
144
        if (inject.appLogger) {
4✔
145
          delete inject.simpleLogger;
1✔
146
          inject.simpleLogger = inject.appLogger;
1✔
147
        }
148

149
        return new ErrorHandler({ inject, ...options });
4✔
150
      });
151
    },
152
);
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc