In this session, we're delving into error handling within Node.js and Express.js. As a robot needs instructions for instances when an object cannot be found, our code similarly requires mechanisms for handling errors.
Error handling is a procedure that detects and manages errors during program execution. Unhandled errors, generated by Syntax Errors (breaches of JavaScript rules), and Runtime Errors (exceptions during execution), can disrupt programs — akin to a robot attempting to find a non-existent object.
The try
statement examines a block of code for errors. Any existing errors are "caught" by the catch
block, thus providing error management.
In this piece of code, instead of letting the program crash (due to the issue that num
is not defined), we "catch" the error and handle it gracefully.
Effective error handling enhances user experience by utilizing appropriate HTTP status codes (e.g., HTTP 200
signifies success, HTTP 404
denotes a resource not found, HTTP 500
denotes an internal server error) within the API.
