-
-
Notifications
You must be signed in to change notification settings - Fork 16
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
Why not use object/class as output similar like Rust Result (Ok/Err class) instead of array? #22
Comments
This is the way to go, this is already solved in standard JS |
The first of all Rust's The second, So, |
This proposal aims to increase the usage of try/catch expressions and error handling, not to create a helper Tuples were chosen because they are simple and makes total sense for that context. const [[error1, data1], [error2, data2]] = await Promise.allSettled(fn1(), fn2()) Which is far less readable than just what we are trying to achieve here: const [error, data] = try fn() // new syntax chosen by community |
With all due respect, how is it possible to refer to Rust in the Proposal Motivation and claim that I have published the one ... @cardellini/ts-result ... and what do I have? import { Result, ok, err } from '@cardellini/ts-result';
type JsonObject = Record<string, unknown>;
const okIfObject = (value: unknown): Result<JsonObject, 'ERR_NOT_AN_OBJECT'> =>
typeof value === 'object' && value !== null && !Array.isArray(value)
? ok(value as JsonObject)
: err('ERR_NOT_AN_OBJECT');
const okIfInt = (value: unknown): Result<number, 'ERR_NOT_AN_INT'> =>
Number.isInteger(value)
? ok(value as number)
: err('ERR_NOT_AN_INT');
const okIfString = (value: unknown): Result<string, 'ERR_NOT_A_STRING'> =>
typeof value === 'string'
? ok(value)
: err('ERR_NOT_A_STRING');
type Person = {
name: string;
age: number;
}
const okIfPerson = (value: unknown): Result<Person, 'ERR_NOT_A_PERSON'> =>
Do(function*() {
const obj = yield* okIfObject(value);
const name = yield* okIfString(obj.name);
const age = yield* okIfInt(obj.age);
return { name, age };
}).mapErr(() => 'ERR_NOT_A_PERSON');
const person: Person = okIfPerson({ name: 'John', age: 42 }).unwrap(); I have to use generators to write monadic code in imperative style. I'd like to write something like that: const okIfPerson = (value: unknown) => {
const obj = try? okIfObject(value);
const name = try? okIfString(obj.name);
const age = try? okIfInt(obj.age);
return { name, age };
}
const person = try! okIfPerson({ name: 'John', age: 42 });
So, while this Proposal pretends to In the same time this proposal could be easlity replaced with simple helper, that is indeed helper: import doTry from 'do-try-tuple';
function div(a: number, b: number): number {
if (b !== 0) return a / b;
if (a !== 0) throw new Error(`Division by Zero`);
throw new Error('Indeterminate Form');
}
const [errX, x] = doTry(() => div(4, 2));
if (errX == null) {
const doubleX = x * 2;
console.log('doubleX:', doubleX);
} Or something like dotry, that even supports iterators and async iterators: import _try from "dotry";
async function* iterateAsync(...data: number[]) {
for (let num of data) {
if (num > 9) {
throw new RangeError(`number ${num} is out of range`);
} else {
yield num;
}
}
}
for await (let [err, value] of _try(iterateAsync, 1, 2, 3, 4)) {
// ...
}
// Or
for await (let [err, value] of _try(iterateAsync(1, 2, 3, 4))) {
// ...
} To write own implementation is also -- not a big deal ... |
Thank you @DScheglov. I am also 100% into creating a monadic error handling mechanism. Current proposal is just “resembling” that idea but in reality doesn’t go beyond being a dangerous syntactic sugar. |
@anacierdem |
@DScheglov i hope you can see the example you brought up is very verbose and confusing for first readers. The above would require a npm package to be installed, so it will be out of at least 99% of tutorials out there, so we will still see patterns like The package you created also has not web bundles, so anyone trying to use it in his simple And so on... |
Let's take you as an example, you talk so much about how a lib is so simple to use and that there is no reason to facilitate error handling in JS. If we search for Exactly, other peoples code could crash because you haven't handled the case where Don't you think that if just by getting used to add And i'm not bashing you in any sense, is just that the above happens to literally everyone. |
Could you please be more conrete here -- I've brought up too many samples
Perhaps, you will be surprised, but not each thrown exception must be caught directly on the function call. As instance, do you know that
Am I talking?? I'm talking that to write own is so simple! yes I'm!
There are three HUGE problems in this statement
async function getData() {
const [requestError, response] ?= await fetch(
"https://api.example.com/data"
)
if (requestError) {
handleRequestError(requestError)
return
}
} Yes, it is easy! To write To handle errors is not easy! My approach to errors is the following:
It doesn't seems to be easy, but it is my rules to write function like
In general I'm excited with the proposal, and everything I'm writing, I'm writing exactly to improve it. Bashing me ... you welcome to do that -- It will help me to become better. |
Prerequisites
Versions
A minimal reproducible example
https://github.com/luolapeikko/result-option/blob/main/test/Result.test.ts
Description
Array is kind of problematic output as then you have two values to resolve again, so I would like to see something like Rust Result like setup.
Steps to Reproduce
Expected Behavior
No response
The text was updated successfully, but these errors were encountered: