Member-only story
Safe Assignment Operators: A New JavaScript Proposal to Say Goodbye to Try Catch!
Error handling has always been an important but complex issue in modern web development. conventional try-catch
Although statements are powerful, they can easily lead to lengthy and difficult to maintain code.
To simplify this process,ECMAScript
A new proposal has recently been introduced:proposal-safe-assignment-operator
The 'Safe Assignment Operator' is denoted as?=
)。
Summary of Proposal
Secure assignment operator?=
The goal is to simplify error handling.
It handles errors by converting the result of a function into an array.
- If the function throws an error, the operator returns
[error, null]
; - If the function is successfully executed, return
[null, result]
。
This operator andPromise、async
Functions and any implementationSymbol.result
The values of the method are compatible.
For example, when executingI/O
Operation or based onPromise
During API interaction, unexpected errors may occur at runtime.
If these errors are ignored, it may lead to unexpected behavior and potential security vulnerabilities. Using secure assignment operators can effectively handle these errors:
const [error, response] ?= await fetch("https://blog.conardli.top");