camptocamp / ogc-client

A TypeScript library for interacting with geospatial services
https://camptocamp.github.io/ogc-client/
BSD 3-Clause "New" or "Revised" License
66 stars 12 forks source link

Return error object instead of message #82

Closed vprintempsPei closed 2 weeks ago

vprintempsPei commented 3 weeks ago

Currently the error on endpoint only returns a message, and then the following console.log(error.httpStatus) returns undefined:

// someWrongUrl can be, for example: https://data.geopf.fr/wts?SERVICE=WMTS&VERSION=1.0.0
this.endpoint = new WmtsEndpoint(someWrongUrl);
try {
  await this.endpoint.isReady();
} catch (e) {
  console.log(e.httpStatus); 
  // returns undefined
  this.error = e.message;
  // returns a message
}

This behavior is due to the following line in eventHandler (utils.ts):

try {
  response = await handler(request.params);
} catch (e) {
  error = e;
}

It can be fixed as follows:

const eventHandler = async (request: WorkerRequest) => {
  if (request.taskName === taskName) {
    let response;

    // !! Update here !!
    let error: EndpointError;
    try {
      response = await handler(request.params);
    } catch (e) {

      // !! Update here !!
      error = {
        httpStatus: e.httpStatus,
        message: e.message,
        name: e.name
      };

    }
    const message = /** @type {WorkerResponse} */ {
      taskName,
      requestId: request.requestId,
      ...(response && { response }),
      ...(error && { error }),
    };
    if (useWorker) {
      scope.postMessage(message);
    } else {
      scope.dispatchEvent(
        new CustomEvent('ogc-client.response', {
          detail: message,
        })
      );
    }
  }
};

This pull request aims to return an error object that contains the error message in error.message and all other error information like httpStatus. Tests have been updated accordingly.

Let me know if i need to change/fix anything in the PR as i don't understand very well the eventHandler function

jahow commented 3 weeks ago

Hi @vprintempsPei , thanks for this PR. I looked into it and I feel like this shouldn't be needed. There can be different kinds of exception when loading an Endpoint (either EndpointError or ServiceExceptionError) and any of them can be returned. If there's no http code, then maybe it's because the error is not an HTTP error?

jahow commented 3 weeks ago

Thank you for raising this issue, indeed there was a problem where the specialized error types were reset in certain scenario! I created a bigger PR to address this and also improve the test coverage of that part.