3 ms·
I feel like TypeScript would make this easy? You can define your functions as returning Error or some other type: function something(...):Error|<something
by nielsbot 7y ago
I feel like TypeScript would make this easy?
You can define your functions as returning Error or some other type:
function something(...):Error|<something else> {
...
}
Also, define `isError(...)`, like so:
function isError(value: Error | any): pet is Error {
return Object.hasPrototype( value, Error )
}
You'd still have the if clauses, but maybe that's not so bad:
function doStuff():Error|Result {
let value = functionReturningValueOrError()
if (value is Error) { return value }
let value = otherFunctionReturningValueOrError()
if (value is Error) { return value }
...
}
- remram 7y agoI also feel like this approach is a lot more valuable in languages that use static typing, such as Rust, Java, and TypeScript. In a yolo-typed language, it is just as easy to forget to handle the return type or the thrown exception.