Search code examples
admin-on-rest

Is it safe to (can I) use `HttpError` from 'admin-on-rest/lib/util/HttpError'?


My API provider is sending error messages in the response.body as a ReadableStream as plain text and I need to get admin-on-rest to display those messages to the end user.

I'm planning to do so like this:

import HttpError from 'admin-on-rest/lib/util/HttpError'
import _ from 'lodash';

function handleError(response) {
  if (_.isFunction(response.text)) {
    const statusText = response.statusText;
    const status = response.status;
    return response.text().then(text => { // get the text from the ReadableStream
      return Promise.reject(new HttpError( text || statusText, status));
    });
  } else { throw new Error(response.statusText); }
}

And in my custom REST Client

//...
if (response.status < 200 || response.status >= 300) {
    return handleError(response);
}
//...

But I feel that accessing to HttpError directly through 'admin-on-rest/lib/util/HttpError' intead of 'admin-on-rest' is insecure because if the internal implementation changes (or there is a refactor of the internal classes of the framework, etc) my implementation will fail.

I cannot do import HttpError from 'admin-on-rest/lib/util/HttpError' because it doesn't work that way. I get __WEBPACK_IMPORTED_MODULE_0_admin_on_rest___default.a is not a constructor

  • So, would be safe to import HttpError like this or not: import HttpError from 'admin-on-rest/lib/util/HttpError'?
  • If no, would it be any other alternative?

Solution

  • A simple(er) and safe(er) alternative can be just not to use HttpError at all.

    Instead do Promise.reject with a simple object as argument, which contains a message and status properties like this:

    //...
    return response.text().then(text => {
      return Promise.reject({message: text || statusText, status: status});
    });
    //...