-1

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

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
  • It depends upon your method of programming for asynchronous operations. Express will automatically catch synchronous exceptions, but not asynchronous ones. And, no framework has an ability to catch asynchronous exceptions that occur in plain callbacks. So, please show coding examples if you want more specific help. The general answer for any type of asynchronous error is "no". For specific coding methods, you can patch the framework to handle rejected promises that are propagated back to the framework or returned errors. – jfriend00 Sep 19 '22 at 08:20
  • See [Async/await in Express](https://stackoverflow.com/questions/61086833/async-await-in-express-middleware/61087195#61087195) for one example. – jfriend00 Sep 19 '22 at 08:21

1 Answers1

0

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 ;