Since we now know how to implement an error handler, we can apply the error handler strategy to our order-api project. First, create a file called errorHandler.ts in the src/utility folder, with the following content:
import { NextFunction, Request, Response } from 'express'
export let logging = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
console.log(err)
next(err)
}
export let clientErrorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
if (req.xhr) {
res.status(500).send({ error: 'Something failed!' })
} else {
next(err)
}
}
export let errorHandler = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
res.status(500).send({ error: err.message })
}
As you can see, we used the same idea of logging, client error, and default error handler code, which will be used throughout the code base.
Now, change the app.ts file to tell Express.js which error handler functions should be used, as follows:
import * as bodyParser from 'body-parser'
import * as express from 'express'
import * as mongoose from 'mongoose'
import { APIRoute } from '../src/routes/api'
import { OrderRoute } from '../src/routes/order'
import { UserRoute } from '../src/routes/user'
import * as errorHandler from '../src/utility/errorHandler'
class App {
public app: express.Application
public userRoutes: UserRoute = new UserRoute()
public apiRoutes: APIRoute = new APIRoute()
public orderRoutes: OrderRoute = new OrderRoute()
public mongoUrl: string = 'mongodb://localhost/order-api'
constructor() {
this.app = express()
this.app.use(bodyParser.json())
this.userRoutes.routes(this.app)
this.apiRoutes.routes(this.app)
this.orderRoutes.routes(this.app)
this.mongoSetup()
this.app.use(errorHandler.logging)
this.app.use(errorHandler.clientErrorHandler)
this.app.use(errorHandler.errorHandler)
}
private mongoSetup(): void {
mongoose.connect(
this.mongoUrl,
{ useNewUrlParser: true }
)
}
}
export default new App().app
Remember to include the error handler functions at the end of the app.use definition.
We now have a custom error handler strategy. Every time that something goes wrong, first the logger handler will catch the error, then it will pass it to the client error handler, and if the error is an xhr type error, it will send a 500 error; otherwise, it will pass it to the catch-all error message.