Skip to content

Errors ​

Every error the engine throws on purpose is an instance of RbacError, and each one has a machine-readable code. Errors from your adapter or database (connection failures, constraint violations) are not wrapped and reach you unchanged.

ts
import { RbacError } from '@anievo-id/rbac-evolution'

try {
  await rbac.for(user).assignRole('ghost')
} catch (error) {
  if (error instanceof RbacError) {
    console.log(error.code)    // 'ROLE_DOES_NOT_EXIST'
    console.log(error.name)    // 'RoleDoesNotExist'
    console.log(error.message) // 'There is no role named `ghost` for guard `web`.'
  }
  throw error
}

Error classes ​

All classes extend RbacError, which extends Error, and all are exported from @anievo-id/rbac-evolution.

ClasscodeThrown when
PermissionDoesNotExistPERMISSION_DOES_NOT_EXISTA permission name can't be found in the guard.
PermissionAlreadyExistsPERMISSION_ALREADY_EXISTScreatePermission is called with a name that already exists in the guard.
RoleDoesNotExistROLE_DOES_NOT_EXISTA role name can't be found in the guard and team.
RoleAlreadyExistsROLE_ALREADY_EXISTScreateRole is called with a name that already exists in the same guard and team.
GuardDoesNotMatchGUARD_DOES_NOT_MATCHA Role or Permission object belongs to a different guard than the current scope.
InvalidWildcardPermissionINVALID_WILDCARD_PERMISSIONWith wildcard: true, a permission name is malformed (empty, or has an empty part or subpart like articles..edit or articles.edit,).

These codes are thrown as plain RbacError instances. Use error.code to tell them apart:

codeThrown when
TEAMS_NOT_ENABLEDA team option (other than null/undefined) is passed while createRbac({ teams: true }) is not set.
TEAM_DOES_NOT_MATCHA Role object from another team is used in a team scope. Global roles (teamId: null) are always allowed.
INVALID_NAMEA role or permission name is empty or only whitespace. Names are trimmed before use.
INVALID_SYNC_DEFINITIONThe definition passed to rbac.sync() is malformed (wrong shape, empty names, a role listed twice in one scope). Thrown before anything is written.
ADAPTER_METHOD_MISSINGThe call needs an optional adapter method that the adapter doesn't implement: teams() and revokeAll({ allTeams: true }) need getSubjectLinks(), deleteTeam() needs getTeamLinks(). Thrown before anything is written. Every built-in adapter has them. Also thrown by an adapter that declares supportsExpiry without the expiry methods.
EXPIRY_NOT_SUPPORTEDAn expiresAt date was given to assignRole, givePermissionTo, syncRoles or syncPermissions, but the adapter doesn't store expiry (it was created without { expiry: true }). Thrown before anything is written, so the link is never stored as permanent. See Temporary access.

The RbacErrorCode type is the union of all twelve codes. New codes can be added in a minor release, so give a switch on it a default branch.

Where each error comes from ​

MethodCan throw
createPermissionPermissionAlreadyExists, InvalidWildcardPermission, INVALID_NAME
createRoleRoleAlreadyExists, TEAMS_NOT_ENABLED, INVALID_NAME
findPermissionOrFail / findRoleOrFailPermissionDoesNotExist / RoleDoesNotExist
deletePermission / deleteRolePermissionDoesNotExist / RoleDoesNotExist; deleteRole with team also TEAMS_NOT_ENABLED
assignRole, removeRole, syncRolesRoleDoesNotExist, GuardDoesNotMatch, TEAM_DOES_NOT_MATCH; with an expiresAt, EXPIRY_NOT_SUPPORTED (and a TypeError for an invalid Date)
givePermissionTo, revokePermissionTo, syncPermissions (subject or role)PermissionDoesNotExist, GuardDoesNotMatch; on a role, also RoleDoesNotExist if the role is missing; on a subject with an expiresAt, EXPIRY_NOT_SUPPORTED
hasPermissionTo, hasDirectPermissionPermissionDoesNotExist (only when wildcard is off), GuardDoesNotMatch
subjectsWithRole / subjectsWithPermissionRoleDoesNotExist / PermissionDoesNotExist, GuardDoesNotMatch
rbac.for(...), rbac.role(...) with teamTEAMS_NOT_ENABLED (thrown synchronously)
revokeAllADAPTER_METHOD_MISSING (only with allTeams and teams enabled)
teamsTEAMS_NOT_ENABLED, ADAPTER_METHOD_MISSING
deleteTeamTEAMS_NOT_ENABLED, ADAPTER_METHOD_MISSING; a TypeError for null or '' (the global scope)
pruneExpiredADAPTER_METHOD_MISSING (an adapter with supportsExpiry but no deleteExpiredLinks())
can, cannot, canAny, canAll, hasAnyPermission, hasAllPermissionsNever throw an RbacError (see below)
hasRole, hasAnyRole, hasAllRoles, hasExactRolesNever throw for unknown names. They return false.

Because any method can also fail with an adapter or database error, wrap writes in your usual error handling.

can() vs hasPermissionTo() ​

Both answer "does this subject have this permission?", but they are meant for different jobs:

hasPermissionTo(p)can(p)
Unknown permission nameThrows PermissionDoesNotExist (wildcard off)Returns false
Other RbacErrors (guard mismatch, ...)ThrowsReturns false
before hookNot appliedApplied first
superAdminRolesNot appliedApplied after before
Adapter / database errorsThrownThrown
Use it forData checks, admin tooling, tests: a typo should fail loudlyAuthorization in routes, middleware and UI
ts
const rbac = createRbac({ adapter, superAdminRoles: ['super-admin'] })
const root = rbac.for({ type: 'user', id: 1 })
await root.assignRole('super-admin')

await root.can('edit artcles')             // true: super-admins pass every can()
await root.hasPermissionTo('edit artcles') // throws PermissionDoesNotExist (typo)

const guest = rbac.for({ type: 'user', id: 2 })
await guest.can('edit artcles')            // false: the error is swallowed

cannot(p) is !can(p). canAny / canAll call can for each permission. hasAnyPermission / hasAllPermissions are pure data checks like hasPermissionTo, but they return false instead of throwing.

TIP

A typo in a permission name passed to can() fails silently, because the check simply returns false. Use typed names so the compiler catches it.

Handling errors in an API ​

ts
import { RbacError } from '@anievo-id/rbac-evolution'

function toHttpStatus(error: RbacError): number {
  switch (error.code) {
    case 'ROLE_DOES_NOT_EXIST':
    case 'PERMISSION_DOES_NOT_EXIST':
      return 404
    case 'ROLE_ALREADY_EXISTS':
    case 'PERMISSION_ALREADY_EXISTS':
      return 409
    default:
      return 422 // invalid name, guard/team mismatch, bad wildcard, teams disabled
  }
}

app.post('/users/:id/roles', async (req, res) => {
  try {
    await rbac.for({ type: 'user', id: req.params.id }).assignRole(req.body.role)
    res.status(204).end()
  } catch (error) {
    if (error instanceof RbacError) {
      return res.status(toHttpStatus(error)).json({ code: error.code, message: error.message })
    }
    throw error
  }
})

Duplicates under race conditions

createRole and createPermission look up the name before inserting. If two requests create the same name at the same moment, both can pass that check. The second insert is then stopped by the database's unique index, and you get the adapter's error (for example Prisma P2002), not RoleAlreadyExists. Use findOrCreateRole / findOrCreatePermission in seed scripts.

Released under the MIT License. Inspired by spatie/laravel-permission.