Skip to content

Commit

Permalink
feat: improve error debugging
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Dec 18, 2022
1 parent 33aa238 commit 1fba504
Show file tree
Hide file tree
Showing 21 changed files with 97 additions and 59 deletions.
8 changes: 4 additions & 4 deletions core/fetch/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function serviceRequest<TData = Record<string, unknown>, TMeta = Re
response = await fetch(options);
}
catch (err) {
logger.error('serviceRequest', (err as Error).message || 'fetch_failed', (err as Error).stack || err, options);
logger.error('serviceRequest', 'fetch_failed', err, options);
throw new Error('fetch_failed');
}

Expand All @@ -46,7 +46,7 @@ export async function serviceRequest<TData = Record<string, unknown>, TMeta = Re
responseText = await response.text();
}
catch (err) {
logger.error('serviceRequest', 'invalid_response', (err as Error).message || err, {
logger.error('serviceRequest', 'invalid_response', err, {
response,
});
throw new Error('invalid_response');
Expand All @@ -57,7 +57,7 @@ export async function serviceRequest<TData = Record<string, unknown>, TMeta = Re
responseJson = JSON.parse(responseText);
}
catch (err) {
logger.error('serviceRequest', 'invalid_json', (err as Error).message || err, {responseText});
logger.error('serviceRequest', 'invalid_json', err, {responseText});
throw new Error('invalid_json');
}

Expand Down Expand Up @@ -289,7 +289,7 @@ async function _handleRetryPattern(options: Required<FetchOptions>): Promise<Res
throw new Error('fetch_server_error');
}
catch (err) {
logger.accident('fetch', 'fetch_failed_retry', (err as Error)?.message ?? 'fetch failed and retry', err);
logger.accident('fetch', 'fetch_failed_retry', (err as Error)?.message || 'fetch failed and retry', err);

await _wait(options.retryDelay);

Expand Down
2 changes: 1 addition & 1 deletion core/i18n/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ l10n.resourceChangeSignal.setProvider(async (locale) => {
}
}
catch (err) {
logger.error('resourceProvider', 'fetch_failed', (err as Error).stack || err, {locale, url});
logger.error('resourceProvider', 'fetch_failed', err, {locale, url});
// TODO: user error signal.
return;
}
Expand Down
6 changes: 3 additions & 3 deletions core/logger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ try {
...
}
catch (err) {
logger.error('myMethod', 'error_code', (err as Error).stack || err, {a: 1, b: 2});
logger.error('myMethod', 'error_code', err, {a: 1, b: 2});
}
```

Expand All @@ -175,7 +175,7 @@ Best practices to catch the error and log it:
```ts
// Unhandled promise rejection (just log it)
failPromiseTest().catch((err) =>
logger.error('myMethod', (err as Error).message || 'error_code', (err as Error).stack || err)
logger.error('myMethod', (err as Error).message || 'error_code', err)
);

// Handled promise rejection
Expand All @@ -186,7 +186,7 @@ try {
'myMethod',
'error_code',
'failPromiseTest failed!, ' + (err as Error).message,
(err as Error).stack || err
err
);
// do something to handle the error...
}
Expand Down
4 changes: 2 additions & 2 deletions core/logger/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,11 @@ export interface AlwatrLogger {
* ...
* }
* catch (err) {
* logger.error('myMethod', 'error_code', (err as Error).stack || err, {a: 1, b: 2});
* logger.error('myMethod', 'error_code', err, {a: 1, b: 2});
* }
* ```
*/
error(method: string, code: string, errorStack: string | unknown, ...args: unknown[]): void;
error(method: string, code: string, ...args: unknown[]): void;

/**
* Simple `console.debug` with styled scope.
Expand Down
8 changes: 7 additions & 1 deletion core/nano-server/src/nano-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ export class AlwatrNanoServer {
this._notFoundListener(connection);
}
}
catch (err) {
catch (_err) {
const err = _err as Error;
this._logger.error('handleRequest', 'http_server_middleware_error', err, {
method: connection.method,
route,
Expand All @@ -256,6 +257,11 @@ export class AlwatrNanoServer {
ok: false,
statusCode: 500,
errorCode: 'http_server_middleware_error',
meta: {
name: err?.name,
message: err?.message,
cause: err?.cause,
},
});
}
}
Expand Down
6 changes: 3 additions & 3 deletions core/signal/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ function __callListeners<SignalName extends keyof AlwatrSignals>(signal: SignalO
const ret = listener.callback(signal.value);
if (ret instanceof Promise) {
ret.catch((err) =>
logger.error('_callListeners', 'call_listener_failed', (err as Error).stack || err, {
logger.error('_callListeners', 'call_listener_failed', err, {
signalName: signal.name,
}),
);
}
}
catch (err) {
logger.error('_callListeners', 'call_listener_failed', (err as Error).stack || err, {
logger.error('_callListeners', 'call_listener_failed', err, {
signalName: signal.name,
});
}
Expand Down Expand Up @@ -129,7 +129,7 @@ export function _addSignalListener<SignalName extends keyof AlwatrSignals>(
listenerCallback(signal.value);
}
catch (err) {
logger.error('_addSignalListener', 'call_signal_callback_failed', (err as Error).stack || err, {
logger.error('_addSignalListener', 'call_signal_callback_failed', err, {
signalName: signal.name,
});
}
Expand Down
2 changes: 1 addition & 1 deletion core/storage-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ try {
if ((err as Error)?.message === 'document_not_found') {
console.log('user_5000 id not found!');
} else {
console.err((err as Error)?.message ?? err);
console.error(err);
}
}
```
Expand Down
19 changes: 10 additions & 9 deletions core/storage-client/src/storage-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ alwatrRegisteredList.push({
* }
*/
export class AlwatrStorageClient<DocumentType extends AlwatrDocumentObject = AlwatrDocumentObject> {
protected _logger = createLogger('alwatr-storage-client:' + this.config.name, undefined, this.config.debug);
protected _logger = createLogger(
'alwatr-storage-client' + (this.config.name == null ? '' : ':' + this.config.name),
undefined,
this.config.debug,
);

/**
* Default fetch options.
Expand Down Expand Up @@ -98,7 +102,7 @@ export class AlwatrStorageClient<DocumentType extends AlwatrDocumentObject = Alw
* console.log('user_5000 id not found!');
* }
* else {
* console.err((err as Error)?.message ?? err);
* console.err((err as Error)?.message || err);
* }
* }
* ```
Expand All @@ -107,7 +111,7 @@ export class AlwatrStorageClient<DocumentType extends AlwatrDocumentObject = Alw
documentId: string,
storage: string | undefined = this.config.name,
): Promise<T> {
this._logger.logMethodArgs('get', {documentId});
this._logger.logMethodArgs('get', {storage, documentId});
if (storage == null) throw new Error('storage_not_defined');

const responseJson = await serviceRequest<T>({
Expand All @@ -118,10 +122,7 @@ export class AlwatrStorageClient<DocumentType extends AlwatrDocumentObject = Alw
},
});

if (
typeof responseJson.data !== 'object' ||
typeof responseJson.data.id !== 'string'
) {
if (typeof responseJson.data !== 'object' || typeof responseJson.data.id !== 'string') {
this._logger.error('get', 'invalid_response_data', {responseJson});
throw new Error('invalid_response_data');
}
Expand All @@ -142,7 +143,7 @@ export class AlwatrStorageClient<DocumentType extends AlwatrDocumentObject = Alw
* ```
*/
async has(documentId: string, storage: string | undefined = this.config.name): Promise<boolean> {
this._logger.logMethodArgs('has', {documentId});
this._logger.logMethodArgs('has', {storage, documentId});
if (storage == null) throw new Error('storage_not_defined');

const responseJson = await serviceRequest<{has: boolean | unknown}>({
Expand Down Expand Up @@ -212,7 +213,7 @@ export class AlwatrStorageClient<DocumentType extends AlwatrDocumentObject = Alw
* ```
*/
async delete(documentId: string, storage: string | undefined = this.config.name): Promise<void> {
this._logger.logMethodArgs('delete', {documentId});
this._logger.logMethodArgs('delete', {storage, documentId});
if (storage == null) throw new Error('storage_not_defined');

await serviceRequest({
Expand Down
2 changes: 1 addition & 1 deletion demo/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ try {
throw new Error('my_error_message');
}
catch (err) {
logger1.error('myMethod', 'error_code', (err as Error).stack || err, {a: 1, b: 2});
logger1.error('myMethod', 'error_code', err, {a: 1, b: 2});
}
5 changes: 1 addition & 4 deletions demo/storage-client/benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ interface User extends AlwatrDocumentObject {
token: string;
}

const token = process.env.TOKEN;
if (token == null) {
throw new Error('token_not_defined');
}
const token = process.env.TOKEN ?? 'YOUR_SECRET_TOKEN';

const db = new AlwatrStorageClient<User>({
name: 'junk-data',
Expand Down
2 changes: 1 addition & 1 deletion services/comment/src/lib/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ import {AlwatrStorageClient} from '@alwatr/storage-client';
import {config} from '../config.js';
import {Message} from './type.js';

export const storage = new AlwatrStorageClient<Message>(config.storage);
export const storageClient = new AlwatrStorageClient<Message>(config.storage);
17 changes: 13 additions & 4 deletions services/comment/src/route/patch.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {config, logger} from '../config.js';
import {nanoServer} from '../lib/nano-server.js';
import {storage} from '../lib/storage.js';
import {storageClient} from '../lib/storage.js';
import {Message} from '../lib/type.js';

import type {AlwatrConnection} from '@alwatr/nano-server';
Expand All @@ -27,17 +27,26 @@ async function setComment(connection: AlwatrConnection): Promise<void> {
// }

try {
const comment = await storageClient.set(bodyJson, params.storage);
logger.logProperty('comment', comment);

connection.reply({
ok: true,
data: await storage.set(bodyJson, params.storage),
data: comment,
});
}
catch (err) {
logger.error('setComment', (err as Error).message ?? 'storage_error', (err as Error).stack ?? err);
catch (_err) {
const err = _err as Error;
logger.error('setComment', err.message || 'storage_error', err);
connection.reply({
ok: false,
statusCode: 500,
errorCode: 'storage_error',
meta: {
name: err.name,
message: err.message,
cause: err.cause,
},
});
}
}
14 changes: 10 additions & 4 deletions services/comment/src/route/storage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {config, logger} from '../config.js';
import {nanoServer} from '../lib/nano-server.js';
import {storage} from '../lib/storage.js';
import {storageClient} from '../lib/storage.js';

import type {AlwatrConnection} from '@alwatr/nano-server';

Expand All @@ -16,14 +16,20 @@ async function getStorage(connection: AlwatrConnection): Promise<void> {
if (params == null) return;

try {
connection.reply(await storage.getStorage(params.name));
connection.reply(await storageClient.getStorage(params.name));
}
catch (err) {
logger.error('getStorage', (err as Error).message ?? 'storage_error', (err as Error).stack ?? err);
catch (_err) {
const err = _err as Error;
logger.error('getStorage', err.message || 'storage_error', err);
connection.reply({
ok: false,
statusCode: 500,
errorCode: 'storage_error',
meta: {
name: err.name,
message: err.message,
cause: err.cause,
},
});
}
}
2 changes: 1 addition & 1 deletion services/flight-crawler/src/crawl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function crawlAllJobs(): Promise<void> {
await storageClient.set(job);
}
catch (err) {
logger.error('crawlAllJobs', 's', (err as Error).stack);
logger.error('crawlAllJobs', 'crawling_failed', err);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions services/storage-server/demo.http
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Content-Type: application/json
{
"id": "auto_increment",
"from": "Ali Mihandoost",
"message": "Salam"
"message": "سلام"
}

###
Expand All @@ -28,7 +28,7 @@ Content-Type: application/json
{
"id": "auto_increment",
"from": "Fateme Mihandoost",
"message": "Aleyk Salam"
"message": "علیک سلام"
}

### Edit document
Expand Down
4 changes: 2 additions & 2 deletions services/telegram-notifier/src/bot/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ export async function launchBot(): Promise<void> {
logger.logProperty('botInfo', bot.botInfo);

bot.launch().catch((err) => {
logger.error('launchBot', 'launch_bot_failed', (err as Error).stack || err);
logger.error('launchBot', 'launch_bot_failed', err);
});

await sendMessage(config.telegramBot.debugNotifyToken, '⚡️ Bot launched');
}
catch (err) {
logger.error('launchBot', 'launch_bot_failed', (err as Error).stack || err);
logger.error('launchBot', 'launch_bot_failed', err);
}
}
2 changes: 1 addition & 1 deletion services/telegram-notifier/src/bot/send-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function sendMessage(to: string, message: string): Promise<void> {
}
catch (err) {
// TODO: handle blocked user
logger.error('sendMessage', 'error_send_message', (err as Error).stack || err, {chatId});
logger.error('sendMessage', 'error_send_message', err, {chatId});
}
}
}
4 changes: 2 additions & 2 deletions ui-kit/icon/src/icon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ export class AlwatrIcon extends AlwatrElement {
try {
this._icon = html`${unsafeSVG(await preloadIcon(this.name, this.urlPrefix))}`;
}
catch (error) {
this._logger.error('_fetchIcon', 'fetch_failed', (error as Error).stack || error);
catch (err) {
this._logger.error('_fetchIcon', 'fetch_failed', err);
this._icon = AlwatrIcon._fallback;
}
}
Expand Down
25 changes: 16 additions & 9 deletions uniquely/flight-finder-api/src/route/job/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,26 @@ async function deleteJob(connection: AlwatrConnection): Promise<void> {
data: {},
});
}
catch (err) {
if ((err as Error).message === 'document_not_found') {
return connection.reply({
catch (_err) {
const err = _err as Error;
if (err.message === 'document_not_found') {
connection.reply({
ok: false,
statusCode: 404,
errorCode: 'document_not_found',
});
}
// else
connection.reply({
ok: false,
statusCode: 500,
errorCode: 'storage_error',
});
else {
connection.reply({
ok: false,
statusCode: 500,
errorCode: 'storage_error',
meta: {
name: err.name,
message: err.message,
cause: err.cause,
},
});
}
}
}
Loading

0 comments on commit 1fba504

Please sign in to comment.