tayfunakgc / express-joi-validation

Middleware Based Joi Validation in ExpressJS
1 stars 4 forks source link

async support? #1

Open kaihendry opened 2 years ago

kaihendry commented 2 years ago

Hi, love this starter, but how do I allow for async code in the handler?

app.get("/", async function (req, res) {
  const octocat = await axios({
    method: "get",
    url: "https://api.github.com/users/octocat",
  });
  console.log(octocat.data);
  throw new Error("test"); // Why isn't this handled?
});
tayfunakgc commented 2 years ago

You can do something like this;

// in app.js
app.get('/', async (req, res, next) => {
    try {
        //* logic here
        throw new Error('test')
    } catch (err) {
        next(err)
    }
})

Not tested but it should work and i think you will get this json response(http://localhost:3000)

{
    "error":{
        "status":500,
        "message":"test"
    }
}
alexadamm commented 1 year ago

Or you can use express 5 instead, route handlers or middleware that return a Promise will call next(value) automatically when they reject or throw an error. So, you don't have to use try catch statement.