Guides

Error Handling

Handle permission check failures gracefully

What it does

Permission checks can fail for several reasons: database errors, cache issues, invalid user IDs, malformed permissions. Error handling ensures your app gracefully recovers instead of crashing.

When to use it

Handle errors when:

  • Database is down — queries fail
  • Invalid permissions — permission name is malformed
  • Setup failed — setupPermissions() wasn't called
  • Bad input — user ID is null or undefined

Always wrap permission checks in try-catch in production.

How it works

  1. Check throws an error (database, invalid input, etc.)
  2. Catch the error and decide what to do
  3. Fail safely — deny access by default

Always assume errors mean "deny access" unless proven otherwise.

Examples

import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

try {
  const allowed = await perms.user(42).can("posts.edit");
  
  if (allowed) {
    console.log("User can edit");
  } else {
    console.log("Access denied");
  }
} catch (error) {
  console.error("Permission check failed:", error);
  console.log("Denying access due to error");
}
import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

try {
  const allowed: boolean = await perms.user(42).can("posts.edit");
  
  if (allowed) {
    console.log("User can edit");
  }
} catch (error) {
  console.error("Permission check failed:", error);
}

In Express middleware

Wrap middleware to handle errors:

import express from "express";
import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

const app = express();

// Minimal auth middleware (reads user ID from header)
app.use((req, res, next) => {
  const userId = req.headers["x-user-id"];
  if (userId) req.user = { id: parseInt(userId) };
  next();
});

// Custom middleware to check permissions safely
async function checkPermission(req, res, next) {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({ error: "Not authenticated" });
    }
    
    const allowed = await perms.user(userId).can("posts.edit");
    
    if (!allowed) {
      return res.status(403).json({ error: "Access denied" });
    }
    
    next();
  } catch (error) {
    console.error("Permission check error:", error);
    res.status(500).json({ error: "Internal server error" });
  }
}

app.post("/posts/:id", checkPermission, (req, res) => {
  res.json({ ok: true });
});
import express from "express";
import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

const app = express();

// Minimal auth middleware (reads user ID from header)
app.use((req, res, next) => {
  const userId = req.headers["x-user-id"];
  if (userId) (req as any).user = { id: parseInt(userId as string) };
  next();
});

async function checkPermission(
  req: express.Request & { user?: { id: number } },
  res: express.Response,
  next: express.NextFunction
) {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({ error: "Not authenticated" });
    }
    
    const allowed = await perms.user(userId).can("posts.edit");
    
    if (!allowed) {
      return res.status(403).json({ error: "Access denied" });
    }
    
    next();
  } catch (error) {
    console.error("Permission check error:", error);
    res.status(500).json({ error: "Internal server error" });
  }
}

app.post("/posts/:id", checkPermission, (_req, res) => {
  res.json({ ok: true });
});

Validate input

Always validate user IDs and permission names using perms.isPermission():

import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

async function checkAccess(userId, permission) {
  // Validate inputs
  if (!userId) {
    throw new Error("User ID required");
  }
  
  if (!perms.isPermission(permission)) {
    throw new Error("Invalid permission");
  }
  
  try {
    return await perms.user(userId).can(permission);
  } catch (error) {
    console.error("Check failed:", error);
    return false; // Deny by default on error
  }
}

const allowed = await checkAccess(42, "posts.edit");
console.log(allowed);
import { perms, setupPermissions, type Permission } from "./permly.js";

await setupPermissions();

async function checkAccess(userId: unknown, permission: unknown): Promise<boolean> {
  if (!userId || typeof userId !== "number") {
    throw new Error("Invalid user ID");
  }
  
  // Validate permission name using isPermission()
  if (!perms.isPermission(permission)) {
    throw new Error("Invalid permission");
  }
  
  // After validation, cast to Permission for type safety
  const validPermission = permission as Permission;
  
  try {
    return await perms.user(userId).can(validPermission);
  } catch (error) {
    console.error("Check failed:", error);
    return false;
  }
}

Distinguish error types

Different errors need different handling:

import { perms, setupPermissions } from "./permly.js";

await setupPermissions();

async function checkAccess(userId, permission) {
  try {
    return await perms.user(userId).can(permission);
  } catch (error) {
    if (error.code === "ECONNREFUSED") {
      // Database is down
      console.error("Database unavailable");
      return false; // Deny access
    } else if (error.code === "SETUP_NOT_CALLED") {
      // Setup failed
      console.error("permly not initialized");
      return false;
    } else {
      // Unknown error
      console.error("Unexpected error:", error);
      return false;
    }
  }
}
import { perms, setupPermissions, type Permission } from "./permly.js";

await setupPermissions();

async function checkAccess(userId: number, permission: Permission): Promise<boolean> {
  try {
    return await perms.user(userId).can(permission);
  } catch (error) {
    if (error instanceof Error) {
      if (error.message.includes("ECONNREFUSED")) {
        console.error("Database unavailable");
      }
    }
    return false;
  }
}

const result = await checkAccess(42, "posts.edit");
console.log(result); // false

Common mistakes

Not catching errors in async code — Permission checks are async. Always use try-catch or .catch().

Allowing access on error — On error, deny access (fail closed). Never allow access when unsure.

Not logging errors — Log permission errors for debugging. Don't silently swallow them.

Assuming errors mean invalid permissions — An error might mean the database is down, not that the permission is invalid.