How to use @feathersjs/errors - 10 common examples

To help you get started, we’ve selected a few @feathersjs/errors examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github feathersjs / feathers / packages / authentication / src / hooks / authenticate.ts View on Github external
const { provider, authentication } = params;
    const authService = app.defaultAuthentication(settings.service);

    debug(`Running authenticate hook on '${path}'`);

    if (type && type !== 'before') {
      throw new NotAuthenticated('The authenticate hook must be used as a before hook');
    }

    if (!authService || typeof authService.authenticate !== 'function') {
      throw new NotAuthenticated('Could not find a valid authentication service');
    }

    // @ts-ignore
    if (service === authService) {
      throw new NotAuthenticated('The authenticate hook does not need to be used on the authentication service');
    }

    if (params.authenticated === true) {
      return context;
    }

    if (authentication) {
      const authParams = omit(params, 'provider', 'authentication', 'query');

      debug('Authenticating with', authentication, strategies);

      const authResult = await authService.authenticate(authentication, authParams, ...strategies);

      context.params = Object.assign({}, params, omit(authResult, 'accessToken'), { authenticated: true });

      return context;
github feathersjs / feathers / packages / authentication / src / hooks / authenticate.ts View on Github external
return async (context: HookContext) => {
    const { app, params, type, path, service } = context;
    const { strategies } = settings;
    const { provider, authentication } = params;
    const authService = app.defaultAuthentication(settings.service);

    debug(`Running authenticate hook on '${path}'`);

    if (type && type !== 'before') {
      throw new NotAuthenticated('The authenticate hook must be used as a before hook');
    }

    if (!authService || typeof authService.authenticate !== 'function') {
      throw new NotAuthenticated('Could not find a valid authentication service');
    }

    // @ts-ignore
    if (service === authService) {
      throw new NotAuthenticated('The authenticate hook does not need to be used on the authentication service');
    }

    if (params.authenticated === true) {
      return context;
    }

    if (authentication) {
      const authParams = omit(params, 'provider', 'authentication', 'query');

      debug('Authenticating with', authentication, strategies);
github feathersjs-ecosystem / feathers-permissions / lib / index.js View on Github external
const { params, type, method } = context;
    const currentPermissions = await Promise.resolve(typeof permissions === 'function' ? permissions(context) : permissions);

    if (type !== 'before') {
      throw new Error('The feathers-permissions hook should only be used as a \'before\' hook.');
    }

    debug('Running checkPermissions hook with options:', { entityName, field, roles: permissions });

    const entity = context.params[entityName];

    if (!entity) {
      debug(`hook.params.${entityName} does not exist. If you were expecting it to be defined check your hook order and your idField options in your auth config.`);

      if (params.provider) {
        throw new Forbidden('You do not have the correct permissions (invalid permission entity).');
      }

      return context;
    }

    // Normalize permissions. They can either be a comma separated string or an array.
    const value = get(entity, field, []);
    const permissionList = typeof value === 'string'
      ? value.split(',').map(current => current.trim()) : value;
    const requiredPermissions = [
      '*',
      `*:${method}`
    ];

    currentPermissions.forEach(permission => requiredPermissions.push(
      `${permission}`,
github Human-Connection / Embed-API / src / services / embeds / embeds.class.js View on Github external
]
    });
    if (embed) {
      return embed.metadata;
    }

    // 2. if not or not older then x minutes, get fresh data and save it to the database
    let metadata = await getMetadata(url, Provider);
    try {
      metadata = Provider.enrichMetadata(metadata);
    } catch (err) {
      // console.error(err);
    }

    if (!metadata.title && !metadata.site_name) {
      throw new errors.NotFound('no data found for url');
    }

    try {
      await this.embeds.create({
        url,
        metadata
      });
    } catch (err) {
      // console.error(err);
    }

    // 3. return cached or fresh metadata
    return metadata;
  }
github feathersjs / feathers / packages / express / lib / rest / getHandler.js View on Github external
return function (req, res, next) {
      const { query } = req;
      const route = omit(req.params, '__feathersId');

      res.setHeader('Allow', allowedMethods.join(','));

      // Check if the method exists on the service at all. Send 405 (Method not allowed) if not
      if (typeof service[method] !== 'function') {
        debug(`Method '${method}' not allowed on '${req.url}'`);
        res.status(statusCodes.methodNotAllowed);

        return next(new errors.MethodNotAllowed(`Method \`${method}\` is not supported by this endpoint.`));
      }

      // Grab the service parameters. Use req.feathers
      // and set the query to req.query merged with req.params
      const params = Object.assign({
        query, route
      }, req.feathers);

      Object.defineProperty(params, '__returnHook', {
        value: true
      });

      const args = getArgs(req, params);

      debug(`REST handler calling \`${method}\` from \`${req.url}\``);
github feathersjs-ecosystem / feathers-knex / lib / error-handler.js View on Github external
// Omit query information
    const messages = error.message.split('-');
    error.message = messages[messages.length - 1];

    switch (error.code.slice(0, 2)) {
      case '22':
      case '23':
        feathersError = new errors.BadRequest(message);
        break;
      case '28':
        feathersError = new errors.Forbidden(message);
        break;
      case '3D':
      case '3F':
      case '42':
        feathersError = new errors.Unprocessable(message);
        break;
      default:
        feathersError = new errors.GeneralError(message);
        break;
    }
  } else if (!(error instanceof errors.FeathersError)) {
    feathersError = new errors.GeneralError(message);
  }

  feathersError[ERROR] = error;

  throw feathersError;
};
github feathersjs-ecosystem / feathers-hooks-common / lib / services / populate.js View on Github external
.then(() => {
        // 'options.schema' resolves to { permissions: '...', include: [ ... ] }

        const items = getItems(context);
        const options1 = Object.assign({}, optionsDefault, options);
        const { schema, checkPermissions } = options1;
        const schema1 = typeof schema === 'function' ? schema(context, options1) : schema;
        const permissions = schema1.permissions || null;
        const baseService = schema1.service;
        const provider = ('provider' in schema1) ? schema1.provider : context.params.provider;

        if (typeof checkPermissions !== 'function') {
          throw new errors.BadRequest('Permissions param is not a function. (populate)');
        }

        if (baseService && context.path && baseService !== context.path) {
          throw new errors.BadRequest(`Schema is for ${baseService} not ${context.path}. (populate)`);
        }

        if (permissions && !checkPermissions(context, context.path, permissions, 0)) {
          throw new errors.BadRequest('Permissions do not allow this populate. (populate)');
        }

        if (typeof schema1 !== 'object') {
          throw new errors.BadRequest('Schema does not resolve to an object. (populate)');
        }

        const include = []
          .concat(schema1.include || [])
github feathersjs-ecosystem / authentication / lib / hooks / authenticate.js View on Github external
hook.data = hook.data || {};

    const strategy = hook.data.strategy || strategies[0];

    if (strategies.indexOf(strategy) === -1) {
      return Promise.reject(new NotAuthenticated(`Strategy ${strategy} is not permitted`));
    }

    // Handle the case where authenticate hook was registered without a passport strategy specified
    if (!strategy) {
      return Promise.reject(new errors.GeneralError(`You must provide an authentication 'strategy'`));
    }

    // The client must send a `strategy` name.
    if (!app.passport._strategy(strategy)) {
      return Promise.reject(new errors.BadRequest(`Authentication strategy '${strategy}' is not registered.`));
    }

    // NOTE (EK): Passport expects an express/connect
    // like request object. So we need to create one.
    let request = {
      query: hook.data,
      body: hook.data,
      params: hook.params,
      headers: hook.params.headers || {},
      cookies: hook.params.cookies || {},
      session: {}
    };

    const strategyOptions = merge({}, app.passport.options(strategy), options);

    debug(`Attempting to authenticate using ${strategy} strategy with options`, strategyOptions);
github feathersjs-ecosystem / feathers-knex / lib / error-handler.js View on Github external
break;
      case '08':
      case '0A':
      case '0K':
        feathersError = new errors.Unavailable(message);
        break;
      case '20':
      case '21':
      case '22':
      case '23':
      case '24':
      case '25':
      case '40':
      case '42':
      case '70':
        feathersError = new errors.BadRequest(message);
        break;
      default:
        feathersError = new errors.GeneralError(message);
    }
  } else if (error.code === 'SQLITE_ERROR') {
    // NOTE (EK): Error codes taken from
    // https://www.sqlite.org/c3ref/c_abort.html
    switch (error.errno) {
      case 1:
      case 8:
      case 18:
      case 19:
      case 20:
        feathersError = new errors.BadRequest(message);
        break;
      case 2:
github feathersjs / feathers / packages / authentication / src / service.ts View on Github external
async remove (id: string | null, params: Params) {
    const { authentication } = params;
    const { authStrategies } = this.configuration;

    // When an id is passed it is expected to be the authentication `accessToken`
    if (id !== null && id !== authentication.accessToken) {
      throw new NotAuthenticated('Invalid access token');
    }

    debug('Verifying authentication strategy in remove');

    return this.authenticate(authentication, params, ...authStrategies);
  }