elastic / kibana

Your window into the Elastic Stack
https://www.elastic.co/products/kibana
Other
19.62k stars 8.22k forks source link

[http] allow capturing caught errors from http handler #161085

Open pgayvallet opened 1 year ago

pgayvallet commented 1 year ago

Related to https://github.com/elastic/kibana/issues/156803

In https://github.com/elastic/kibana/pull/161063, we modified the error handling of the http router to manually call apm.captureError when an error is thrown from the handler. This was required because we're shallowing the actual error and not passing it down to HAPI to avoid stacktraces to surfaces from our APIs (for security concerns).

However, if that allows to record errors explicitly thrown from the handler, e.g

    router.get({ path: '/', validate: false }, (context, req, res) => {
      throw new Error(`some error`);
    });

there is currently no way to capture errors associated to "errors responses", e.g

    router.get({ path: '/', validate: false }, (context, req, res) => {
      try {
        doSomething();
        return res.ok();
      } catch(e) {
        return res.customError({ statusCode: 500, body: 'something went wrong'})
      }
    });

Which forces the handler's owner to manually capture the error:

https://github.com/elastic/kibana/blob/ac2fc4c3beca7b677910815566db55b93d8406a7/x-pack/plugins/apm/server/routes/apm_routes/register_apm_server_routes.ts#L183-L191

Ideally, capturing errors related to handler exception would be centralized at Core's level.

We could, for example, change the KibanaResponseFactory API to support a new error option, that would, if provided, be simply captured.

The previous snippet could then be changed to:

    router.get({ path: '/', validate: false }, (context, req, res) => {
      try {
        doSomething();
        return res.ok();
      } catch(e) {
        return res.customError({ statusCode: 500, body: 'something went wrong', error: e})
      }
    });

or, to reuse the APM snippet:

 [...]

 return response.custom({ ...opts, error }); 
elasticmachine commented 1 year ago

Pinging @elastic/kibana-core (Team:Core)