Skip to main content

Error Handling

Error Handling is a very important part of any application. It is important to handle errors gracefully and present them to the user in a way that is understandable. This is especially true for applications that are used by non-technical users. We use express-async-errors to handle errors in our application. This package allows us to use async/await syntax in our express routes and automatically catch any errors that occur.

Error Middleware

We have a middleware function that is responsible for catching errors and sending them to the user. This middleware function is called after all other middleware functions and routes have been called. This allows us to catch any errors that occur in our application.

// middlewares/error.middleware.js

const methods = require("../helpers/methods")
const errorLog = require("simple-node-logger").createSimpleLogger({
logFilePath: "./log/error/" + new Date().toLocaleDateString().split("/").join("-") + ".log",
timestampFormat: "YYYY-MM-DD HH:mm:ss"
})
/**
*
* @param error
* @param req
* @param res
* @param next
* @returns {*}
*/
// eslint-disable-next-line no-unused-vars
module.exports = (error, req, res, next) => {
errorLog.error(error.message)
return res.status(process.env.EXCEPTION_CODE).send(methods.failResponse(error.message))
}

Error Logging

We use simple-node-logger to log errors to a file. This allows us to keep track of errors that occur in our application. We log the error message and the stack trace to the file. We also log the date and time that the error occurred. log file names are formatted as YYYY-MM-DD.log. This allows us to easily find the log file for a specific date. We also use the timestampFormat option to format the date and time that the error occurred. This makes it easier to read the log file. Log files are stored in the log/error directory.

Error Response

The failResponse method is used to format the error message and send it to the user. This method is defined in the method helper file. The failResponse method takes a message as a parameter and returns an object with the message and a status code. You can change the status code to whatever you want in .env. We use 400 because it is the standard status code for a bad request.

Support Framework X

  • You can also support the project by following the organization and Star ⭐ the project on GitHub
  • Contribute by submitting issues and pull requests
  • Share the project with your friends and colleagues, any and all support is appreciated. 🙏
  • If you find this Framework useful, We will always appreciate a strong cup of coffee.