Skip to content

Commit 1186525

Browse files
committed
add utility for creating exception-safe "runner" functions
1 parent 1d2be77 commit 1186525

File tree

2 files changed

+40
-10
lines changed

2 files changed

+40
-10
lines changed

packages/unraid-api-plugin-connect/src/service/url-resolver.service.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
22
import { ConfigService } from '@nestjs/config';
33

44
import { URL_TYPE } from '@unraid/shared/network.model.js';
5+
import { makeSafeRunner } from '@unraid/shared/util/processing.js';
56

67
import { ConfigType } from '../model/connect-config.model.js';
78

@@ -268,17 +269,13 @@ export class UrlResolverService {
268269
const errors: Error[] = [];
269270
const urls: AccessUrl[] = [];
270271

271-
const doSafely = (fn: () => void) => {
272-
try {
273-
fn();
274-
} catch (error: unknown) {
275-
if (error instanceof Error) {
276-
errors.push(error);
277-
} else {
278-
this.logger.warn(error, 'Uncaught error in network resolver');
279-
}
272+
const doSafely = makeSafeRunner((error) => {
273+
if (error instanceof Error) {
274+
errors.push(error);
275+
} else {
276+
this.logger.warn(error, 'Uncaught error in network resolver');
280277
}
281-
};
278+
});
282279

283280
doSafely(() => {
284281
const defaultUrl = new URL(nginx.defaultUrl);
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Utils related to processing operations
2+
// e.g. parallel processing, safe processing, etc.
3+
4+
/**
5+
* Creates a function that runs a given function and catches any errors.
6+
* If an error is caught, it is passed to the `onError` function.
7+
*
8+
* @param onError - The function to call if an error is caught.
9+
* @returns A function that runs the given function and catches any errors.
10+
* @example
11+
* const errors: Error[] = [];
12+
* const doSafely = makeSafeRunner((error) => {
13+
* if (error instanceof Error) {
14+
* errors.push(error);
15+
* } else {
16+
* this.logger.warn(error, 'Uncaught error in network resolver');
17+
* }
18+
* });
19+
*
20+
* doSafely(() => {
21+
* JSON.parse(aFile);
22+
* throw new Error('test');
23+
* });
24+
*/
25+
export function makeSafeRunner(onError: (error: unknown) => void) {
26+
return <T>(fn: () => T) => {
27+
try {
28+
return fn();
29+
} catch (error) {
30+
onError(error);
31+
}
32+
};
33+
}

0 commit comments

Comments
 (0)