You need to be able to handle errors when they happen within your server. This lesson will show you how to do it.
Let’s begin by creating errors.
Creating Errors
The easiest way to create errors is to use the http-errors package.
Let’s start by installing this package.
npm install http-errors -SYou can throw errors in your routes with the following syntax:
import createError from 'http-errors'
app.route('/link-to-resource', (req, res) => { throw createError(httpStatus, errorMessage)})httpStatus: The response status.errorMessage: This is an optional value that contains the error message you want to return. It is not thestatusText. (ThestatusTextwill be sent automatically).
Make sure you replace httpStatus and errorMessage with appropriate values!
Here’s an example of a real error message:
app.route('/link-to-resource', (req, res) => { throw createError(400, 'Wrong password')})Next, all errors that are thrown in your routes will be handled in an error handler.
The error handler
Express lets handle all errors in an error handler.
This error handler takes in 4 values and should be used as your final route.
// All other routes should go here// Error handlerapp.use((err, req, res, next) => { // ...})In this handler, you need to do two things:
- Set the
status - Send a response.
If you have thrown errors with the http-errors package, you will be able to handle all errors with the following code:
// Send errors back to the requesterapp.use((err, req, res, next) => { const status = err.status || 500 res.status(status) res.json({ code: status, message: err.message, stack: err.stack, })})Now if you try to send a request to http://localhost:3000/link-to-resource, you should get an error that says wrong password.
Handling 404 — Not Found
You also have to handle routes that your server doesn’t support. You can do this by adding another route before your error handler.
In this route, you throw a 404 error.
// All other routes here...// Throw 404 errorapp.use((req, res) => throw createError(404))// Error handler hereThat’s all you need to know about error handling!
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson