nodejs how to send error response automatically if anything fails

Viewed 24

In Nodejs, for every api i am using try/catch block, if everything works i return the response with 200 and in catch block i need to use the res.status(500).send()

is there any way i can avoid using try/catch like if anything fails, some middleware or anything can catch the error and send the error response to user.

Like in NestJS you just simply use the return response, no need to even use res.send to send the response, if there is error it automatically send the 500 response

1 Answers

in the main mjs file:

import { expressError } from "expressError.mjs //pathpath";

app.all("*", (req, res, next) => {
  next(new expressError("page not found", 404));
});
app.use((err, req, res, next) => {
  // console.log(err);
  // return res.json("fail");
  const { statuscode = 500 } = err;
  if (!err.message) err.message = "something went wrong!!!";
  res.status(statuscode).send(err)
});

in the expressError.mjs file :

export class expressError extends Error {
  constructor(message, statuscode) {
    super();
    this.message = message;
    this.statuscode = statuscode;
  }
}

in the main js file:

const { expressError } = require("expressError.js //path");

app.all("*", (req, res, next) => {
  next(new expressError("page not found", 404));
});
app.use((err, req, res, next) => {
  // console.log(err);
  // return res.json("fail");
  const { statuscode = 500 } = err;
  if (!err.message) err.message = "something went wrong!!!";
  res.status(statuscode).send(err)
});

in the expressError.js file :

 class expressError extends Error {
  constructor(message, statuscode) {
    super();
    this.message = message;
    this.statuscode = statuscode;
  }
}
module.exports = expressError ;
Related