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.
In this context, we use try/catch
for handling server-side exceptions, and catch
dispatches an HTTP status code 500 (Internal Server Error) for server errors.
In a full-stack application, both client and server errors require attention.
For the server, consider the following:
On the client side (React with Axios), the catch
block manages errors during the GET request.
Today, we have covered error handling, try/catch
blocks, error handling in APIs, and a full-stack application. By avoiding application crashes and providing valuable feedback, proper error handling proves beneficial. Prepare for forthcoming practice tasks, where your learning is enhanced by practical application. Remember, to err is human; to handle is divine!
