Simplify work with errors

This commit is contained in:
Anton Vakhrushev 2020-04-20 21:48:34 +03:00
parent fec538be86
commit 4ff55b5850
9 changed files with 40 additions and 46 deletions

View File

@ -31,12 +31,12 @@ export class ActionController {
ensureSameVillage(args: Args, task: Task) { ensureSameVillage(args: Args, task: Task) {
let villageId = args.villageId; let villageId = args.villageId;
if (villageId === undefined) { if (villageId === undefined) {
throw new ActionError(task.id, 'Undefined village id'); throw new ActionError('Undefined village id');
} }
const activeVillageId = grabActiveVillageId(); const activeVillageId = grabActiveVillageId();
if (villageId !== activeVillageId) { if (villageId !== activeVillageId) {
throw new TryLaterError(task.id, aroundMinutes(1), 'Not same village'); throw new TryLaterError(aroundMinutes(1), 'Not same village');
} }
} }
} }

View File

@ -12,14 +12,14 @@ export class BuildBuildingAction extends ActionController {
const buildTypeId = args.buildTypeId; const buildTypeId = args.buildTypeId;
if (buildTypeId === undefined) { if (buildTypeId === undefined) {
throw new ActionError(task.id, 'Undefined build type id'); throw new ActionError('Undefined build type id');
} }
try { try {
clickBuildButton(buildTypeId); clickBuildButton(buildTypeId);
} catch (e) { } catch (e) {
if (e instanceof GrabError) { if (e instanceof GrabError) {
throw new TryLaterError(task.id, aroundMinutes(5), 'No upgrade button, try later'); throw new TryLaterError(aroundMinutes(5), 'No upgrade button, try later');
} }
throw e; throw e;
} }

View File

@ -10,7 +10,7 @@ export class CheckBuildingRemainingTimeAction extends ActionController {
async run(args: Args, task: Task): Promise<any> { async run(args: Args, task: Task): Promise<any> {
const info = this.grabBuildingQueueInfoOrDefault(); const info = this.grabBuildingQueueInfoOrDefault();
if (info.seconds > 0) { if (info.seconds > 0) {
throw new TryLaterError(task.id, info.seconds + 1, 'Building queue is full'); throw new TryLaterError(info.seconds + 1, 'Building queue is full');
} }
} }

View File

@ -37,7 +37,7 @@ export class SendOnAdventureAction extends ActionController {
this.checkConfig(easiest, Number(hero.health)); this.checkConfig(easiest, Number(hero.health));
} }
throw new AbortTaskError(task.id, 'No suitable adventure'); throw new AbortTaskError('No suitable adventure');
} }
private checkConfig(adventure: Adventure, health: number) { private checkConfig(adventure: Adventure, health: number) {

View File

@ -7,50 +7,50 @@ import { getNumber, toNumber } from '../utils';
@registerAction @registerAction
export class TrainTrooperAction extends ActionController { export class TrainTrooperAction extends ActionController {
async run(args: Args, task: Task): Promise<any> { async run(args: Args, task: Task): Promise<any> {
const troopId = this.getTroopId(args, task); const troopId = this.getTroopId(args);
const trainCount = this.getTrainCount(args, task); const trainCount = this.getTrainCount(args);
const block = jQuery(`#nonFavouriteTroops .innerTroopWrapper.troop${troopId}`); const block = jQuery(`#nonFavouriteTroops .innerTroopWrapper.troop${troopId}`);
if (block.length !== 1) { if (block.length !== 1) {
throw new ActionError(task.id, `Troop block not found`); throw new ActionError(`Troop block not found`);
} }
const countLink = block.find('.cta a'); const countLink = block.find('.cta a');
if (countLink.length !== 1) { if (countLink.length !== 1) {
throw new ActionError(task.id, `Link with max count not found`); throw new ActionError(`Link with max count not found`);
} }
const maxCount = getNumber(countLink.text()); const maxCount = getNumber(countLink.text());
if (maxCount < trainCount) { if (maxCount < trainCount) {
throw new TryLaterError(task.id, 20 * 60, `Max count ${maxCount} less then need ${trainCount}`); throw new TryLaterError(20 * 60, `Max count ${maxCount} less then need ${trainCount}`);
} }
const input = block.find(`input[name="t${troopId}"]`); const input = block.find(`input[name="t${troopId}"]`);
if (input.length !== 1) { if (input.length !== 1) {
throw new ActionError(task.id, `Input element not found`); throw new ActionError(`Input element not found`);
} }
const trainButton = jQuery('.startTraining.green').first(); const trainButton = jQuery('.startTraining.green').first();
if (trainButton.length !== 1) { if (trainButton.length !== 1) {
throw new ActionError(task.id, 'Train button not found'); throw new ActionError('Train button not found');
} }
input.val(trainCount); input.val(trainCount);
trainButton.trigger('click'); trainButton.trigger('click');
} }
private getTroopId(args: Args, task: Task): number { private getTroopId(args: Args): number {
const troopId = toNumber(args.troopId); const troopId = toNumber(args.troopId);
if (troopId === undefined) { if (troopId === undefined) {
throw new ActionError(task.id, `Troop id must be a number, given "${args.troopId}"`); throw new ActionError(`Troop id must be a number, given "${args.troopId}"`);
} }
return troopId; return troopId;
} }
private getTrainCount(args: Args, task: Task): number { private getTrainCount(args: Args): number {
const trainCount = toNumber(args.trainCount); const trainCount = toNumber(args.trainCount);
if (trainCount === undefined) { if (trainCount === undefined) {
throw new ActionError(task.id, `Train count must be a number, given "${args.trainCount}"`); throw new ActionError(`Train count must be a number, given "${args.trainCount}"`);
} }
return trainCount; return trainCount;
} }

View File

@ -14,7 +14,7 @@ export class UpgradeBuildingAction extends ActionController {
clickUpgradeButton(); clickUpgradeButton();
} catch (e) { } catch (e) {
if (e instanceof GrabError) { if (e instanceof GrabError) {
throw new TryLaterError(task.id, aroundMinutes(5), 'No upgrade button, try later'); throw new TryLaterError(aroundMinutes(5), 'No upgrade button, try later');
} }
throw e; throw e;
} }

View File

@ -1,8 +1,7 @@
import { ActionController, registerAction } from './ActionController'; import { ActionController, registerAction } from './ActionController';
import { Args } from '../Command'; import { Args } from '../Command';
import { ActionError, GrabError, TryLaterError } from '../Errors'; import { ActionError, TryLaterError } from '../Errors';
import { Task } from '../Queue/TaskQueue'; import { Task } from '../Queue/TaskQueue';
import { clickUpgradeButton } from '../Page/BuildingPage';
import { grabResourceDeposits } from '../Page/SlotBlock'; import { grabResourceDeposits } from '../Page/SlotBlock';
import { UpgradeBuildingTask } from '../Task/UpgradeBuildingTask'; import { UpgradeBuildingTask } from '../Task/UpgradeBuildingTask';
import { ResourceDeposit } from '../Game'; import { ResourceDeposit } from '../Game';
@ -13,7 +12,7 @@ export class UpgradeResourceToLevel extends ActionController {
async run(args: Args, task: Task): Promise<any> { async run(args: Args, task: Task): Promise<any> {
const deposits = grabResourceDeposits(); const deposits = grabResourceDeposits();
if (deposits.length === 0) { if (deposits.length === 0) {
throw new ActionError(task.id, 'No deposits'); throw new ActionError('No deposits');
} }
const villageId = args.villageId; const villageId = args.villageId;
@ -39,13 +38,13 @@ export class UpgradeResourceToLevel extends ActionController {
const notUpgraded = deposits.sort((x, y) => x.level - y.level).filter(isDepositTaskNotInQueue); const notUpgraded = deposits.sort((x, y) => x.level - y.level).filter(isDepositTaskNotInQueue);
if (notUpgraded.length === 0) { if (notUpgraded.length === 0) {
throw new TryLaterError(task.id, aroundMinutes(10), 'No available deposits'); throw new TryLaterError(aroundMinutes(10), 'No available deposits');
} }
for (let dep of notUpgraded) { for (let dep of notUpgraded) {
this.scheduler.scheduleTask(UpgradeBuildingTask.name, { villageId, buildId: dep.buildId }); this.scheduler.scheduleTask(UpgradeBuildingTask.name, { villageId, buildId: dep.buildId });
} }
throw new TryLaterError(task.id, aroundMinutes(10), 'Sleep for next round'); throw new TryLaterError(aroundMinutes(10), 'Sleep for next round');
} }
} }

View File

@ -1,5 +1,3 @@
import { TaskId } from './Queue/TaskQueue';
export class GrabError extends Error { export class GrabError extends Error {
constructor(msg: string = '') { constructor(msg: string = '') {
super(msg); super(msg);
@ -8,30 +6,24 @@ export class GrabError extends Error {
} }
export class ActionError extends Error { export class ActionError extends Error {
readonly taskId: TaskId; constructor(msg: string = '') {
constructor(taskId: TaskId, msg: string = '') {
super(msg); super(msg);
this.taskId = taskId;
Object.setPrototypeOf(this, ActionError.prototype); Object.setPrototypeOf(this, ActionError.prototype);
} }
} }
export class AbortTaskError extends Error { export class AbortTaskError extends Error {
readonly taskId: TaskId; constructor(msg: string = '') {
constructor(taskId: TaskId, msg: string = '') {
super(msg); super(msg);
this.taskId = taskId;
Object.setPrototypeOf(this, AbortTaskError.prototype); Object.setPrototypeOf(this, AbortTaskError.prototype);
} }
} }
export class TryLaterError extends Error { export class TryLaterError extends Error {
readonly seconds: number; readonly seconds: number;
readonly taskId: TaskId;
constructor(taskId: TaskId, seconds: number, msg: string = '') { constructor(seconds: number, msg: string = '') {
super(msg); super(msg);
this.taskId = taskId;
this.seconds = seconds; this.seconds = seconds;
Object.setPrototypeOf(this, TryLaterError.prototype); Object.setPrototypeOf(this, TryLaterError.prototype);
} }

View File

@ -43,10 +43,10 @@ export class Executor {
await sleepMicro(); await sleepMicro();
const currentTs = timestamp(); const currentTs = timestamp();
const taskCommand = this.scheduler.nextTask(currentTs); const task = this.scheduler.nextTask(currentTs);
// текущего таска нет, очищаем очередь действий по таску // текущего таска нет, очищаем очередь действий по таску
if (!taskCommand) { if (!task) {
this.logger.log('NO ACTIVE TASK'); this.logger.log('NO ACTIVE TASK');
this.scheduler.clearActions(); this.scheduler.clearActions();
return; return;
@ -54,26 +54,29 @@ export class Executor {
const actionCommand = this.scheduler.nextAction(); const actionCommand = this.scheduler.nextAction();
this.logger.log('CURRENT JOB', 'TASK', taskCommand, 'ACTION', actionCommand); this.logger.log('CURRENT JOB', 'TASK', task, 'ACTION', actionCommand);
this.runGrabbers(); this.runGrabbers();
try { try {
if (actionCommand) { if (actionCommand) {
return await this.processActionCommand(actionCommand, taskCommand); return await this.processActionCommand(actionCommand, task);
} }
if (taskCommand) { if (task) {
return await this.processTaskCommand(taskCommand); return await this.processTaskCommand(task);
} }
} catch (e) { } catch (e) {
this.handleError(e); this.handleError(e, task);
} }
} }
private async processActionCommand(cmd: Command, task: Task) { private async processActionCommand(cmd: Command, task: Task) {
const actionController = createAction(cmd.name, this.scheduler); const actionController = createAction(cmd.name, this.scheduler);
this.logger.log('PROCESS ACTION', cmd.name, actionController); this.logger.log('PROCESS ACTION', cmd.name, actionController);
if (cmd.args.taskId !== task.id) {
throw new ActionError(`Action task id ${cmd.args.taskId} not equal current task id ${task.id}`);
}
if (actionController) { if (actionController) {
await actionController.run(cmd.args, task); await actionController.run(cmd.args, task);
} else { } else {
@ -92,19 +95,19 @@ export class Executor {
} }
} }
private handleError(err: Error) { private handleError(err: Error, task: Task) {
this.scheduler.clearActions(); this.scheduler.clearActions();
if (err instanceof AbortTaskError) { if (err instanceof AbortTaskError) {
this.logger.warn('ABORT TASK', err.taskId); this.logger.warn('ABORT TASK', task.id);
this.scheduler.completeTask(err.taskId); this.scheduler.completeTask(task.id);
this.scheduler.clearActions(); this.scheduler.clearActions();
return; return;
} }
if (err instanceof TryLaterError) { if (err instanceof TryLaterError) {
this.logger.warn('TRY', err.taskId, 'AFTER', err.seconds); this.logger.warn('TRY', task.id, 'AFTER', err.seconds);
this.scheduler.postponeTask(err.taskId, err.seconds); this.scheduler.postponeTask(task.id, err.seconds);
return; return;
} }