[SOLVED] nodejs how to send error response automatically if anything fails

Issue

This Content is from Stack Overflow. Question asked by Sunil Garg

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



Solution

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 ;


This Question was asked in StackOverflow by Sunil Garg and Answered by mohamedszaina It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?