Skip to content

Commit

Permalink
fix(tasks): catches and finalize stop on cancellation
Browse files Browse the repository at this point in the history
  • Loading branch information
rafamel committed Apr 6, 2021
1 parent 4f730e3 commit 7527388
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
10 changes: 7 additions & 3 deletions src/tasks/exception/catches.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Task, Context, LogLevel } from '../../definitions';
import { formatMessage } from '../../helpers/format-message';
import { isCancelled } from '../../utils/is-cancelled';
import { run } from '../../utils/run';
import { log } from '../stdio/log';
import { shallow } from 'merge-strategies';
import { into } from 'pipettes';

export interface CatchesOptions {
/** Logs the error message with a given level. Default: `'info'` */
/** Logs the error message with a given level. Default: `'warn'` */
level?: LogLevel;
}

Expand All @@ -27,10 +29,12 @@ export function catches(
return async (ctx: Context): Promise<void> => {
const opts = shallow({ level: 'warn' }, options || undefined);
try {
await task(ctx);
await run(task, ctx);
} catch (err) {
if (await isCancelled(ctx)) return;

into(ctx, log(opts.level, formatMessage(err)));
if (alternate) await alternate(ctx);
if (alternate) await run(alternate, ctx);
}
};
}
22 changes: 17 additions & 5 deletions src/tasks/exception/finalize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-useless-catch */
import { Task, Context } from '../../definitions';
import { isCancelled } from '../../utils/is-cancelled';
import { run } from '../../utils/run';

/**
* Always executes a `final` task after another.
Expand All @@ -9,12 +10,23 @@ import { Task, Context } from '../../definitions';
*/
export function finalize(task: Task, final?: Task | null): Task.Async {
return async (ctx: Context): Promise<void> => {
const errors: Error[] = [];

try {
await task(ctx);
await run(task, ctx);
} catch (err) {
throw err;
} finally {
if (final) await final(ctx);
errors.push(err);
}

if (await isCancelled(ctx)) return;

try {
if (final) await run(final, ctx);
} catch (err) {
errors.push(err);
}

if (!errors.length || (await isCancelled(ctx))) return;
throw errors.pop();
};
}

0 comments on commit 7527388

Please sign in to comment.