Almost everyone who uses JavaScript daily knows that try-catch can be painful to deal with, especially when you have more than one error to handle.
Most proposed solutions are tryng to copy Golang's approach - which handles everything as return values. It is, among other things, is a great feature of Go, but JS is completely different language (duh) and I think we can do better than a copy-paste from Go.
In Go, when we want to handle an error, we return it from the function call either as a second value in tuple or as return value of the function call. Following is the pattern:
result, error := DoSomething() if error != nil { // handle error }
This approach allows to handle the errors explicitly using standard control flow.
To apply this pattern in javascript the most common solution is to return results as an array:
const handler = async (promise) => { try { const result = await promise() return [result, null]; } catch(error) { return [null, error]; } } const [response, error] = await handle(fetch('http://go.gl')) if (error !== null) { // handle error }
As you can see this is almost direct copy-paste of the pattern from Go.
Returning consistent value
This pattern works great, but in javascript we can do better than this. The core idea of this pattern is to return error as a value, so let's adapt it with better SoC.
Instead of returning null or Error we can decorate the result with a consistent interface. That would improve our SoC, and give us a strongly typed return value:
interface Status { Ok(): boolean; Fail(): boolean; Of(cls: any): boolean; }
The interface Status doesn't have to be an Error, but we can check it's type using status.Of(Error). We can always return an object that sattisfies Status. The usage example would be:
const [response, error] = await handle(res.json()) if (error.Of(SyntaxError)) { // handle error console.log("not a json") return }
Now, in JavaScript our result doesn't always have to be a tuple. We can actually create our own class that behaves as a tuple when it's needed:
interface IResult<t> { 0: T; 1: Status; value: T; status: Status; Of(cls: any): boolean; Ok(): boolean; Fail(): boolean; } </t>
Usage example:
const result = await handle(res.value.json()) if (result.Of(SyntaxError)) { // handle error console.log("not a json") return }
The Implementation
Following this approach I've created ready to use function - Grip.
Grip is strongly typed and can decorate functions and promisises alike.
I use git to host such packages, so to install use github:
bun add github:nesterow/grip # or pnpm
Usage:
The grip function accepts a function or a promise and returns a result with return value and status.
The result can be hadled as either an object or a tuple.
import { grip } from '@nesterow/grip';
Handle result as an object:
The result can be handled as an object: {value, status, Ok(), Fail(), Of(type)}
const res = await grip( fetch('https://api.example.com') ); if (res.Fail()) { handleErrorProperly(); return; } const json = await grip( res.value.json() ); if (json.Of(SyntaxError)) { handleJsonParseError(); return; }
Handle result as a tuple:
The result can also be received as a tuple if you want to handle errors in Go'ish style:
const [res, fetchStatus] = await grip( fetch('https://api.example.com') ); if (fetchStatus.Fail()) { handleErrorProperly(); return; } const [json, parseStatus] = await grip( res.json() ); if (parseStatus.Of(SyntaxError)) { handleJsonParseError(); return; }
If you like this take on error handling check out the repository. The source is about 50LOC, without types, and a 100 with types.
以上がJavaScript での Go スタイルのエラー処理の解釈の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

JavaScript文字列置換法とFAQの詳細な説明 この記事では、javaScriptの文字列文字を置き換える2つの方法について説明します:内部JavaScriptコードとWebページの内部HTML。 JavaScriptコード内の文字列を交換します 最も直接的な方法は、置換()メソッドを使用することです。 str = str.replace( "find"、 "置換"); この方法は、最初の一致のみを置き換えます。すべての一致を置き換えるには、正規表現を使用して、グローバルフラグGを追加します。 str = str.replace(/fi

記事では、JavaScriptライブラリの作成、公開、および維持について説明し、計画、開発、テスト、ドキュメント、およびプロモーション戦略に焦点を当てています。

この記事では、ブラウザでJavaScriptのパフォーマンスを最適化するための戦略について説明し、実行時間の短縮、ページの負荷速度への影響を最小限に抑えることに焦点を当てています。

この記事では、ブラウザ開発者ツールを使用した効果的なJavaScriptデバッグについて説明し、ブレークポイントの設定、コンソールの使用、パフォーマンスの分析に焦点を当てています。

マトリックスの映画効果をあなたのページにもたらしましょう!これは、有名な映画「The Matrix」に基づいたクールなJQueryプラグインです。プラグインは、映画の古典的な緑色のキャラクター効果をシミュレートし、画像を選択するだけで、プラグインはそれを数値文字で満たされたマトリックススタイルの画像に変換します。来て、それを試してみてください、それはとても面白いです! それがどのように機能するか プラグインは画像をキャンバスにロードし、ピクセルと色の値を読み取ります。 data = ctx.getimagedata(x、y、settings.greasize、settings.greasize).data プラグインは、写真の長方形の領域を巧みに読み取り、jQueryを使用して各領域の平均色を計算します。次に、使用します

この記事では、jQueryライブラリを使用してシンプルな画像カルーセルを作成するように導きます。 jQuery上に構築されたBXSLiderライブラリを使用し、カルーセルをセットアップするために多くの構成オプションを提供します。 今日、絵のカルーセルはウェブサイトで必須の機能になっています - 1つの写真は千の言葉よりも優れています! 画像カルーセルを使用することを決定した後、次の質問はそれを作成する方法です。まず、高品質の高解像度の写真を収集する必要があります。 次に、HTMLとJavaScriptコードを使用して画像カルーセルを作成する必要があります。ウェブ上には、さまざまな方法でカルーセルを作成するのに役立つ多くのライブラリがあります。オープンソースBXSLiderライブラリを使用します。 BXSLiderライブラリはレスポンシブデザインをサポートしているため、このライブラリで構築されたカルーセルは任意のものに適合させることができます

キーポイントJavaScriptを使用した構造的なタグ付けの強化は、ファイルサイズを削減しながら、Webページコンテンツのアクセシビリティと保守性を大幅に向上させることができます。 JavaScriptを効果的に使用して、Cite属性を使用して参照リンクを自動的にブロック参照に挿入するなど、HTML要素に機能を動的に追加できます。 JavaScriptを構造化されたタグと統合することで、ページの更新を必要としないタブパネルなどの動的なユーザーインターフェイスを作成できます。 JavaScriptの強化がWebページの基本的な機能を妨げないようにすることが重要です。 高度なJavaScriptテクノロジーを使用できます(

データセットは、APIモデルとさまざまなビジネスプロセスの構築に非常に不可欠です。これが、CSVのインポートとエクスポートが頻繁に必要な機能である理由です。このチュートリアルでは、Angular内でCSVファイルをダウンロードおよびインポートする方法を学びます


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 中国語版
中国語版、とても使いやすい

WebStorm Mac版
便利なJavaScript開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

ホットトピック



