Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Aligning errors #321

Draft
wants to merge 20 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/core/errors/errors.helpers.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { SecurityValues } from '@superfaceai/ast';
import { AssertionError, BackoffKind } from '@superfaceai/ast';

import { SDKBindError, SDKExecutionError } from '../../lib';
import { isRegistryErrorBody } from '../registry';
import { SDKBindError, SDKExecutionError } from './errors';

export function superJsonNotDefinedError(
callerName: string
Expand Down
49 changes: 42 additions & 7 deletions src/core/errors/errors.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,39 @@
import { SDKExecutionError, UnexpectedError } from '../../lib';
import { ErrorBase, SDKExecutionError, UnexpectedError } from './errors';

describe('errors', () => {
describe('ErrorBase', () => {
let error: ErrorBase;

class MyError extends ErrorBase {}

beforeEach(() => {
error = new MyError('MyKind', 'My message');
console.log(error);
});

it('has kind', () => {
expect(error.kind).toBe('MyKind');
});

it('has name', () => {
expect(error.name).toBe('MyKind');
});

it('creates default string description', () => {
expect(Object.prototype.toString.call(error)).toBe('[object MyKind]');
});

it('strigifies kind and message', () => {
expect(error.toString()).toBe('MyKind: My message');
});
});

describe('UnexpectedError', () => {
const error = new UnexpectedError('out of nowhere');
let error: UnexpectedError;

beforeEach(() => {
error = new UnexpectedError('out of nowhere');
});

it('throws in correct format', () => {
expect(() => {
Expand All @@ -16,11 +47,15 @@ describe('errors', () => {
});

describe('SDKExecutionError', () => {
const error = new SDKExecutionError(
'short',
['long1', 'long2', 'long3'],
['hint1', 'hint2', 'hint3']
);
let error: SDKExecutionError;

beforeEach(() => {
error = new SDKExecutionError(
'short',
['long1', 'long2', 'long3'],
['hint1', 'hint2', 'hint3']
);
});

it('only returns the short message when short format is requested', () => {
expect(error.formatShort()).toBe('short');
Expand Down
43 changes: 17 additions & 26 deletions src/lib/error/error.ts → src/core/errors/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,28 @@ export function ensureErrorSubclass(error: unknown): Error {
return new Error(JSON.stringify(error));
}

export class ErrorBase {
constructor(public kind: string, public message: string) {}
export abstract class ErrorBase extends Error {
constructor(kind: string, message: string) {
super(message);
this.name = kind;
}

public get [Symbol.toStringTag](): string {
return this.kind;
return this.name;
}

public get kind(): string {
return this.name;
}

public toString(): string {
return `${this.kind}: ${this.message}`;
public override toString(): string {
return `${this.name}: ${this.message}`;
}
}

export class UnexpectedError extends ErrorBase {
constructor(
public override message: string,
public additionalContext?: unknown
) {
super('UnexpectedError', message);
constructor(message: string, public additionalContext?: unknown) {
super(UnexpectedError.name, message);
}
}

Expand All @@ -34,19 +38,14 @@ export class UnexpectedError extends ErrorBase {
*
* These errors should be as descriptive as possible to explain the problem to the user.
*/
export class SDKExecutionError extends Error {
export class SDKExecutionError extends ErrorBase {
constructor(
private shortMessage: string,
private longLines: string[],
private hints: string[]
) {
super(shortMessage);

// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, SDKBindError.prototype);

super(SDKExecutionError.name, shortMessage);
this.message = this.formatLong();
this.name = 'SDKExecutionError';
}

/**
Expand Down Expand Up @@ -79,10 +78,6 @@ export class SDKExecutionError extends Error {
return result + '\n';
}

public get [Symbol.toStringTag](): string {
return this.name;
}

public override toString(): string {
return this.formatLong();
}
Expand All @@ -91,10 +86,6 @@ export class SDKExecutionError extends Error {
export class SDKBindError extends SDKExecutionError {
constructor(shortMessage: string, longLines: string[], hints: string[]) {
super(shortMessage, longLines, hints);

// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, SDKBindError.prototype);

this.name = 'SDKBindError';
this.name = SDKBindError.name;
}
}
47 changes: 13 additions & 34 deletions src/core/errors/fetch.errors.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,27 @@
import { ErrorBase } from '../../lib';
import { ErrorBase } from './errors';

interface NetworkError {
kind: 'network';
issue: 'unsigned-ssl' | 'dns' | 'timeout' | 'reject';
}

interface RequestError {
kind: 'request';
issue: 'abort' | 'timeout';
}
type NetworkErrorIssue = 'unsigned-ssl' | 'dns' | 'timeout' | 'reject';
type RequestErrorIssue = 'abort' | 'timeout';
type FetchErrorIssue = NetworkErrorIssue | RequestErrorIssue;

export type FetchErrorIssue = NetworkError['issue'] | RequestError['issue'];

export class FetchErrorBase extends ErrorBase {
constructor(public override kind: string, public issue: FetchErrorIssue) {
export abstract class FetchError extends ErrorBase {
constructor(kind: string, public issue: FetchErrorIssue) {
super(kind, `Fetch failed: ${issue} issue`);
}
}

export class NetworkFetchError extends FetchErrorBase {
constructor(public override issue: NetworkError['issue']) {
super('NetworkError', issue);
}

public get normalized(): NetworkError {
return { kind: 'network', issue: this.issue };
export class NetworkFetchError extends FetchError {
constructor(public override issue: NetworkErrorIssue) {
super(NetworkFetchError.name, issue);
}
}

export class RequestFetchError extends FetchErrorBase {
constructor(public override issue: RequestError['issue']) {
super('RequestError', issue);
}

public get normalized(): RequestError {
return { kind: 'request', issue: this.issue };
export class RequestFetchError extends FetchError {
constructor(public override issue: RequestErrorIssue) {
super(RequestFetchError.name, issue);
}
}

export type FetchError = NetworkFetchError | RequestFetchError;

export function isFetchError(input: unknown): input is FetchError {
return (
typeof input === 'object' &&
(input instanceof NetworkFetchError || input instanceof RequestFetchError)
);
return input instanceof FetchError;
}
53 changes: 12 additions & 41 deletions src/core/errors/filesystem.errors.ts
Original file line number Diff line number Diff line change
@@ -1,62 +1,33 @@
import type {
IFileExistsError,
INotEmptyError,
INotFoundError,
IPermissionDeniedError,
IUnknownFileSystemError,
} from '../../interfaces';
import { ErrorBase } from './errors';

export class FileExistsError extends Error implements IFileExistsError {
public override name = 'FileExistsError' as const;
export abstract class FileSystemError extends ErrorBase {}

export class FileExistsError extends FileSystemError {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, FileExistsError.prototype);
super(FileExistsError.name, message);
}
}

export class PermissionDeniedError
extends Error
implements IPermissionDeniedError
{
public override name = 'PermissionDeniedError' as const;

export class PermissionDeniedError extends FileSystemError {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, PermissionDeniedError.prototype);
super(PermissionDeniedError.name, message);
}
}

export class NotEmptyError extends Error implements INotEmptyError {
public override name = 'NotEmptyError' as const;
export class NotEmptyError extends FileSystemError {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, NotEmptyError.prototype);
super(NotEmptyError.name, message);
}
}

export class NotFoundError extends Error implements INotFoundError {
public override name = 'NotFoundError' as const;
export class NotFoundError extends FileSystemError {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, NotFoundError.prototype);
super(NotFoundError.name, message);
}
}

export class UnknownFileSystemError
extends Error
implements IUnknownFileSystemError
{
public override name = 'UnknownFileSystemError' as const;
export class UnknownFileSystemError extends FileSystemError {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, UnknownFileSystemError.prototype);
super(UnknownFileSystemError.name, message);
}
}

export type FileSystemError =
| FileExistsError
| PermissionDeniedError
| NotEmptyError
| NotFoundError
| UnknownFileSystemError;
1 change: 1 addition & 0 deletions src/core/errors/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './errors';
export * from './errors.helpers';
export * from './fetch.errors';
export * from './filesystem.errors';
3 changes: 2 additions & 1 deletion src/core/events/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ import type {
import { ApiKeyPlacement, HttpScheme, SecurityType } from '@superfaceai/ast';
import { getLocal } from 'mockttp';

import { err, UnexpectedError } from '../../lib';
import { err } from '../../lib';
import { MockTimers } from '../../mock';
import { NodeCrypto, NodeFetch, NodeFileSystem } from '../../node';
import { Config } from '../config';
import { UnexpectedError } from '../errors';
import { BoundProfileProvider } from '../profile-provider';
import { ServiceSelector } from '../services';
import { Events } from './events';
Expand Down
4 changes: 2 additions & 2 deletions src/core/events/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type {
ITimers,
LogFunction,
} from '../../interfaces';
import { UnexpectedError } from '../../lib';
import { UnexpectedError } from '../errors';
import type { HttpResponse, IFetch, RequestParameters } from '../interpreter';
import type { UseCase } from '../usecase';
import type { HooksContext } from './failure/event-adapter';
Expand All @@ -38,7 +38,7 @@ export type Interceptable = {
events?: Events;
};

type EventContextBase = {
export type EventContextBase = {
readonly time: Date;
readonly usecase?: string;
readonly profile?: string;
Expand Down
43 changes: 34 additions & 9 deletions src/core/events/failure/event-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import type { ILogger, ITimers } from '../../../interfaces';
import { clone, SDKBindError, UnexpectedError } from '../../../lib';
import { isFetchError } from '../../errors';
import type { Events } from '../events';
import { clone } from '../../../lib';
import {
FetchError,
NetworkFetchError,
RequestFetchError,
SDKBindError,
UnexpectedError,
} from '../../errors';
import type { EventContextBase, Events } from '../events';
import type { FailurePolicyRouter } from './policies';
import type { ExecutionFailure, FailurePolicyReason } from './policy';
import type {
Expand Down Expand Up @@ -362,12 +368,8 @@ function registerNetworkHooks(

let failure: ExecutionFailure;

if (isFetchError(error)) {
failure = {
time: context.time.getTime(),
registryCacheAge: 0, // TODO,
...error.normalized,
};
if (error instanceof FetchError) {
failure = fetchErrorToFailure(context, error);
} else {
failure = {
kind: 'unknown',
Expand Down Expand Up @@ -445,3 +447,26 @@ function registerNetworkHooks(
}
});
}

function fetchErrorToFailure(
context: EventContextBase,
err: FetchError
): ExecutionFailure {
if (err instanceof NetworkFetchError) {
return {
time: context.time.getTime(),
registryCacheAge: 0, // TODO,
kind: 'network',
issue: err.issue,
};
} else if (err instanceof RequestFetchError) {
return {
time: context.time.getTime(),
registryCacheAge: 0, // TODO,
kind: 'request',
issue: err.issue,
};
} else {
throw 'cant reach';
}
}
2 changes: 1 addition & 1 deletion src/core/events/failure/policies.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { UnexpectedError } from '../../../lib';
import { UnexpectedError } from '../../errors';
import type { Backoff } from './backoff';
import type {
ExecutionFailure,
Expand Down
Loading