Skip to content

Better support for async handlers #3429

@rubennorte

Description

@rubennorte

Given that async functions are now standard it'd be great to have better support for them in Hapi. Specifically, using them as handlers:

server.route({
  method: 'GET',
  path: '/',
  handler: async function (request, reply) {
    const data = await getData();
    const other = await getOther(data);
    reply(other);
  }
});

We can use them now as I described but any error in the handler would become an unhandled promise rejection. Catching them in the framework instead of forcing the programmers wrap the code inside a try/catch would be nice. This is what I'd like to avoid:

server.route({
  method: 'GET',
  path: '/',
  handler: async function (request, reply) {
    try {
      const data = await getData();
      const other = await getOther(data);
      reply(other);
    } catch (error) {
      reply(error);
    }
  }
});

Would you accept a PR on this? Would you also use the result of the async function to call reply or only catch the errors?

Thanks for considering this.

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions