简体   繁体   中英

Javascript: error handling

I'm new to javascript, and I'm wondering how I should handle errors. More precisely, when should I use exceptions, return values, callbacks or promises ? I'm currently using return values for synchronous functions, and callbacks/promises for asynchronous functions, but I'm not sure that's a good choice, because I never use exceptions, and I know some people consider that they are very useful, especially when a synchronous function could return usual error values (-1 and null) as correct values, but in practice, it's very rare that -1 and null are both correct results for a function . Someone could tell me how to choose the right solution ?

Problem with return values is not that there isn't values to choose from but the fact that you need to manually check for them and propagate them down the stack.

If an error happens through an exception and you don't have a try-catch anywhere, you will crash the process and see a nice stack trace. The error can either be a bug in code (typically TypeError and ReferenceError) or an expected occurrence like file not existing. In latter case you should add try-catch and handle the file not existing, in former case you should not add try-catch but fix the bug instead.

On the other hand, if you forget to check for an erroneous return value, then the program will probably silently continue in undefined state or some other worse outcome than crashing. There is also the fact that bugs are usually caused by forgetting something so needing to explicitly check return values everywhere is bad.

Another issue is that even if you check for a return value, you might not know at that point how to handle it so you need to manually propagate it further which again requires manual code. With try-catch, the try catch doesn't need to there right now, it can be further down the stack where the error can be handled (like displaying message in UI that "something went wrong").

If you want to handle errors with asynchronous code then you should use promises. Although a minimal promise implementation is still unusable for this, it is still light years ahead of error handling asynchronous code with callbacks which is ridiculous and doesn't only require manual checks and propagations but requires 2 different channels of error handling: synchronous and asynchronous. See What are promises and why should I use them? (Disclaimer: I am the author)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM