Error Handling With Express Flashcards
How can we catch all types of response methods?
We can use the all
method on the app
object.
How can we match any path in our app?
We can use *
to match any URL in our app.
Where would we create middleware to handle unhandled routes?
We want to create the middleware inside our main file.
What are operational errors?
These are predictable errors that we anticipate and handle in advance.
What are Programming errors?
These are bugs or mistakes introduced during development.
How can we implement a global error-handling middleware?
We use the app
method and pass in the arguments (err, req, res, next
).
What do we do inside our global error-handling middleware?
Set up properties to handle the status code, defaulting to 500 if not specified, and the status message, defaulting to ‘error’ if absent.
Next, we will send a response with the status code from the error object and a JSON object containing status
(set to err.status
) and message
(set to err.message
).
How can we call our global error-handling middleware?
We invoke next()
with our error instance as an argument. Calling next()
with an argument triggers the error-handling middleware we previously defined.
Where should we add the error-handling middleware?
You want to create its controller. Export the function, and make a middleware for it in the main file.
How can we create operational errors?
Create a class that extends from the Error
class. This custom class constructor accepts a statusCode
and message
. From the parent Error
class, we only inherit the message
property.
What does isOperational
mean?
Indicates that any error created with this class is an operational error. This distinction will be useful later when handling different types of errors.
What folder should the operational error class be in?
It should be in the utils
folder.
How can we refactor handling async errors?
We can remove all the catch blocks and create a helper function that will handle the errors.
Tell me what should the error helper function have?
It should accept a function as an argument. This function should return a function with req, res, and next passed in. This returned function should execute the passed-in function, chaining it with a catch method that passes the next method. This next method will automatically receive the error object.
How can we handle docs not found in our DB due to bad input?
We want to check if the document was returned. If the document was not found, we want to return a next function with the error class passed in.