Try/Catch Alternative - Simpler Error Handling ⚠️ in JavaScript

preview_player
Показать описание
There are a couple articles and videos about a possible safe assignment operator proposal for ECMAScript/JavaScript. The proposal will not happen but will instead be replaced with a similar try expressions proposal that could possibly happen in the future.

In this video I will show you an alternative way to achieve the same syntax with widely supported JavaScript language features today as these proposals are just syntactic sugar over the try/catch block.

Contents:
0:00 The Safe Assignment Operator Proposal
2:26 How to Use That Syntax Today

Social Media:

#javascript #errorhandling #programming
Рекомендации по теме
Комментарии
Автор

This is what I did. Try is a reserved keyword so it doesn’t work as a function name

/**
* Wraps a function in a try-catch block, returning either an error or a result as a tuple.
* Works seamlessly for both sync and async functions.
*/
export function safe<TArgs extends any[], TResult>(
fn: (...args: TArgs) => Promise<TResult>
): (...args: TArgs) => Promise<[unknown, null] | [null, TResult]>;

export function safe<TArgs extends any[], TResult>(
fn: (...args: TArgs) => TResult
): (...args: TArgs) => [unknown, null] | [null, TResult];

export function safe<TArgs extends any[], TResult>(
fn: (...args: TArgs) => TResult | Promise<TResult>
): (...args: TArgs) => [unknown, null] | [null, TResult] | Promise<[unknown, null] | [null, TResult]> {
return (...args: TArgs): any => {
try {
const result = fn(...args);
if (result instanceof Promise) {
return result
.then((value) => [null, value]) // Success case
.catch((error) => [error, null]); // Error case
}
return [null, result]; // Success case for sync
} catch (error) {
return [error, null]; // Error case for sync
}
};
}

BlazeShomida
Автор

That's really cool, like how it simplifies the code a lot, I guess Rust is actually making other languages better after all

whilelab
Автор

All pages/links you are using in the video should be also in video description

oPOCCOMAXAo
Автор

This is basically Effect TS on steroids if you really wanna make your code more powerful _cough_ _cough_ complex

goosybs
Автор

Absolutely can't understand half the words. It would really help to pronounce when you talk…

NatoBoram
Автор

this can literally be implemented with simple function

function try<T>(f: () => T): Result<T, unknown> {
try {
return { type: "ok", value: f() };
} catch(e) {
return { type: "error", value: e };
}
}
const {type, value} = try(() => someThingThatMightThrow());

coffee-is-power
welcome to shbcf.ru