Skip to content

Commit

Permalink
incr: improve error display
Browse files Browse the repository at this point in the history
- show duplicate error instead of sqlite fail dump
  • Loading branch information
18alantom committed Aug 29, 2022
1 parent 078d1e8 commit afc136d
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 17 deletions.
8 changes: 7 additions & 1 deletion fyo/model/doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { markRaw } from 'vue';
import { isPesa } from '../utils/index';
import {
areDocValuesEqual,
getInsertionError,
getMissingMandatoryMessage,
getPreDefaultValues,
setChildDocIdx,
Expand Down Expand Up @@ -682,7 +683,12 @@ export class Doc extends Observable<DocValue | Doc[]> {
await this._preSync();

const validDict = this.getValidDict(false, true);
const data = await this.fyo.db.insert(this.schemaName, validDict);
let data: DocValueMap;
try {
data = await this.fyo.db.insert(this.schemaName, validDict);
} catch (err) {
throw getInsertionError(err as Error, validDict);
}
await this._syncValues(data);

this.fyo.telemetry.log(Verb.Created, this.schemaName);
Expand Down
37 changes: 36 additions & 1 deletion fyo/model/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Fyo } from 'fyo';
import { DocValue } from 'fyo/core/types';
import { DocValue, DocValueMap } from 'fyo/core/types';
import { isPesa } from 'fyo/utils';
import { DuplicateEntryError } from 'fyo/utils/errors';
import { isEqual } from 'lodash';
import { Money } from 'pesa';
import { Field, FieldType, FieldTypeEnum } from 'schemas/types';
Expand Down Expand Up @@ -114,3 +115,37 @@ export function setChildDocIdx(childDocs: Doc[]) {
childDocs[idx].idx = +idx;
}
}

export function getInsertionError(err: Error, validDict: DocValueMap): Error {
if (err.message.includes('UNIQUE constraint failed:')) {
return getDuplicateEntryError(err, validDict);
}

return err;
}

export function getDuplicateEntryError(
err: Error,
validDict: DocValueMap
): Error | DuplicateEntryError {
const matches = err.message.match(/UNIQUE constraint failed:\s(\w+)\.(\w+)$/);
if (!matches) {
return err;
}

const schemaName = matches[1];
const fieldname = matches[2];
if (!schemaName || !fieldname) {
return err;
}

const duplicateEntryError = new DuplicateEntryError(err.message, false);
duplicateEntryError.stack = err.stack;
duplicateEntryError.more = {
schemaName,
fieldname,
value: validDict[fieldname],
};

return duplicateEntryError;
}
9 changes: 7 additions & 2 deletions fyo/utils/errors.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
export class BaseError extends Error {
more: Record<string, unknown> = {};
message: string;
statusCode: number;
shouldStore: boolean;

constructor(statusCode: number, message: string, shouldStore: boolean = true) {
constructor(
statusCode: number,
message: string,
shouldStore: boolean = true
) {
super(message);
this.name = 'BaseError';
this.statusCode = statusCode;
Expand Down Expand Up @@ -96,7 +101,7 @@ export function getDbError(err: Error) {
return CannotCommitError;
}

if (err.message.includes('SQLITE_CONSTRAINT: UNIQUE constraint failed:')) {
if (err.message.includes('UNIQUE constraint failed:')) {
return DuplicateEntryError;
}

Expand Down
55 changes: 52 additions & 3 deletions src/errorHandling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ export async function handleErrorWithDialog(
const errorMessage = getErrorMessage(error, doc);
await handleError(false, error, { errorMessage, doc });

const name = error.name ?? t`Error`;
const options: MessageDialogOptions = { message: name, detail: errorMessage };
const label = getErrorLabel(error);
const options: MessageDialogOptions = { message: label, detail: errorMessage };

if (reportError) {
options.detail = truncate(options.detail, { length: 128 });
Expand All @@ -106,7 +106,7 @@ export async function handleErrorWithDialog(
reportIssue(getErrorLogObject(error, { errorMessage }));
},
},
{ label: t`OK`, action() {} },
{ label: t`Cancel`, action() {} },
];
}

Expand Down Expand Up @@ -196,3 +196,52 @@ export function reportIssue(errorLogObj?: ErrorLog) {
const urlQuery = getIssueUrlQuery(errorLogObj);
ipcRenderer.send(IPC_MESSAGES.OPEN_EXTERNAL, urlQuery);
}

function getErrorLabel(error: Error) {
const name = error.name;
if (!name) {
return t`Error`;
}

if (name === 'BaseError') {
return t`Error`;
}

if (name === 'ValidationError') {
return t`Validation Error`;
}

if (name === 'NotFoundError') {
return t`Not Found`;
}

if (name === 'ForbiddenError') {
return t`Forbidden Error`;
}

if (name === 'DuplicateEntryError') {
return t`Duplicate Entry`;
}

if (name === 'LinkValidationError') {
return t`Link Validation Error`;
}

if (name === 'MandatoryError') {
return t`Mandatory Error`;
}

if (name === 'DatabaseError') {
return t`Database Error`;
}

if (name === 'CannotCommitError') {
return t`Cannot Commit Error`;
}

if (name === 'NotImplemented') {
return t`Error`;
}

return t`Error`;
}
33 changes: 23 additions & 10 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,14 @@
import { t } from 'fyo';
import { Doc } from 'fyo/model/doc';
import { isPesa } from 'fyo/utils';
import { DuplicateEntryError, LinkValidationError } from 'fyo/utils/errors';
import {
BaseError,
DuplicateEntryError,
LinkValidationError
} from 'fyo/utils/errors';
import { Money } from 'pesa';
import { Field, FieldType, FieldTypeEnum } from 'schemas/types';
import { fyo } from 'src/initFyo';

export function stringifyCircular(
obj: unknown,
Expand All @@ -24,7 +29,8 @@ export function stringifyCircular(
}

if (cacheValue.includes(value)) {
const circularKey = cacheKey[cacheValue.indexOf(value)] || '{self}';
const circularKey: string =
cacheKey[cacheValue.indexOf(value)] || '{self}';
return ignoreCircular ? undefined : `[Circular:${circularKey}]`;
}

Expand Down Expand Up @@ -84,16 +90,23 @@ export function convertPesaValuesToFloat(obj: Record<string, unknown>) {
}

export function getErrorMessage(e: Error, doc?: Doc): string {
let errorMessage = e.message || t`An error occurred.`;
const errorMessage = e.message || t`An error occurred.`;

const { schemaName, name }: { schemaName?: string; name?: string } =
doc ?? {};
const canElaborate = !!(schemaName && name);
let { schemaName, name } = doc ?? {};
if (!doc) {
schemaName = (e as BaseError).more?.schemaName as string | undefined;
name = (e as BaseError).more?.value as string | undefined;
}

if (!schemaName || !name) {
return errorMessage;
}

if (e instanceof LinkValidationError && canElaborate) {
errorMessage = t`${schemaName} ${name} is linked with existing records.`;
} else if (e instanceof DuplicateEntryError && canElaborate) {
errorMessage = t`${schemaName} ${name} already exists.`;
const label = fyo.db.schemaMap[schemaName]?.label ?? schemaName;
if (e instanceof LinkValidationError) {
return t`${label} ${name} is linked with existing records.`;
} else if (e instanceof DuplicateEntryError) {
return t`${label} ${name} already exists.`;
}

return errorMessage;
Expand Down

0 comments on commit afc136d

Please sign in to comment.