To handle errors in asynchronous functions, use try/catch, handle it in the call chain, use the .catch() method, and listen for the unhandledrejection event. 1. Using try/catch to catch errors is the recommended method, with a clear structure and can handle exceptions in await; 2. Handling errors in the call chain can be centralized logic, which is suitable for multi-step processes; 3. Using .catch() can catch errors after calling the async function, which is suitable for Promise combination scenarios; 4. Listen to unhandledrejection events to record unhandled rejections as the last line of defense; the above methods together ensure that asynchronous errors are correctly captured and processed.
Handling errors in asynchronous functions is a very important part of JavaScript development, especially when using async/await. If error handling is ignored, it may cause program crashes, data loss, or problems that are difficult to debug.

In the async/await function, the reject state of the Promise does not automatically throw exceptions to the global scope like the synchronous code, but will exist in the form of an uncaught Promise rejection. Therefore, we need to take the initiative to catch errors, or use other ways to make sure they are handled correctly.
Use try/catch to catch errors
This is the most common and recommended way. The async function can use try/catch
internally to catch possible errors in await expression.

async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return await response.json(); } catch (error) { console.error('Fetch failed:', error); // You can choose to rethrow or return the default value // throw error; return { data: null }; } }
- Advantages : clear structure and intuitive logic.
- Note :
- Don't miss checks for non-2xx responses (such as
!response.ok
above). - If you don't have rethrow in catch, remember to consider whether you need to return a default value or make a bottom-up treatment.
- Don't miss checks for non-2xx responses (such as
Handling errors in the call chain
If you do not want to handle errors inside the async function, you can also throw them out and handle them uniformly at a higher level:
async function stepOne() { const res = await fetch('...'); if (!res.ok) throw new Error('Step one failed'); } async function main() { try { await stepOne(); //Other steps... } catch (err) { console.error('Something went wrong:', err); } }
- The advantage of this is that it can centralize error handling logic, especially suitable for process control composed of multiple steps.
- The downside is that if something goes wrong with an intermediate step but you don't catch, the error will continue to bubble until it is caught or becomes unhandledrejection.
Use .catch() to handle Promise errors
Although async/await is more recommended to use try/catch, you can still use .catch()
after calling the async function:

fetchData() .then(data => console.log('Success:', data)) .catch(err => console.error('Error:', err));
This method is suitable for scenarios where you want to use the async function as a normal promise, such as combining multiple promises or using them for event processing.
Avoid "silent failure": Listen to unhandledrejection
If you forget to handle the error, the browser or Node.js sometimes triggers unhandledrejection
event. You can listen to it to log or do the final remedy:
process.on('unhandledRejection', (reason, promise) => { console.error('Unhandled Rejection at:', promise, 'reason:', reason); });
- This cannot replace normal error handling, but it can help you find those missed errors.
- It is recommended to add this listener to the production environment as the last line of defense.
Basically these are the methods. async/await makes asynchronous code more like synchronous writing, but you still need to pay more attention to error handling, especially in network requests, database operations and other places where errors are prone to errors.
The above is the detailed content of Error Handling in Async/Await JavaScript Functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl
