Wrong errormessage when preventing user creation

System Information
  • Strapi Version: 3.6.2
  • Operating System: Ubuntu Server 20.04 / Mac OSX 11.3
  • Database: MariaDB
  • Node Version: 14.16.0
  • NPM Version: 7.14.0
  • Yarn Version: 1.22.10

I got a question about preventing a save/create in a model.

As a new user registers (POST request to “/auth/local/register”), I have to check if a company exists (by checking the ‘name’ property). If it does exist, prevent the creation of a new user.
Here is how I solved it in the model:

// /extensions/users-permissions/models/User.js
beforeCreate: async (data) => {
  if(data.type == 'company') {
    // check if company exists
    let checkCompany = await strapi.services['companies'].find({ name: data.company.name });
    if(checkCompany.length > 0) {
          throw strapi.errors.badRequest('Company already exists. Not registering your user (and company).');
    }
    const newCompany = await strapi.services['companies'].create(data.company);
    data.company = newCompany.id;
  }
}

This works currently pretty well (technically speaking), but I receive a weird response from strapi to my frontend page:

{"statusCode":400,"error":"Bad Request","message":[{"messages":[{"id":"Auth.form.error.email.taken","message":"Email already taken"}]}],"data":[{"messages":[{"id":"Auth.form.error.email.taken","message":"Email already taken"}]}]}```

Strapi returns the message, that the users’ email is already taken. Anybody got an idea why that happens?

The best case scenario would be to return my own/custom message.

Is there a better approach for this, than mine?

Hey i tried it and worked perfectly:

'use strict';

/**
 * Lifecycle callbacks for the `User` model.
 */

module.exports = {
    lifecycles: {
        beforeCreate(params, populate) {
            throw strapi.errors.badRequest('Company already exists. Not registering your user (and company).');
        },
      },
};

Response:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Company already exists. Not registering your user (and company)."
}

version:

{
  "strapi-plugin-users-permissions": "3.6.2",
}