Blog>
Snippets

Permission Denied Error

Forge a PermissionDeniedError class to represent errors caused by unauthorized access attempts to resources or operations.
class PermissionDeniedError extends Error {
    constructor(message) {
        super(message);
        this.name = 'PermissionDeniedError';
        if (Error.captureStackTrace) {
            Error.captureStackTrace(this, PermissionDeniedError);
        }
    }
}
Defines a custom error class 'PermissionDeniedError' to handle unauthorized access attempts. It extends the built-in Error class and captures the stack trace for debugging purposes.
function checkAccess(user) {
    const hasAccess = user.permissions && user.permissions.includes('admin');
    if (!hasAccess) {
        throw new PermissionDeniedError('User does not have sufficient permissions.');
    }
    // Perform the action that requires admin permissions
}
Example function 'checkAccess' which uses the PermissionDeniedError. If a user does not have the required permission, a new PermissionDeniedError is thrown.
try {
    // Simulate a user object
    const user = { name: 'Jane', permissions: ['user'] };
    checkAccess(user); // This should throw a PermissionDeniedError
} catch (error) {
    if (error instanceof PermissionDeniedError) {
        console.error(error.message); // Handle the permission denied error
    } else {
        console.error('An unexpected error occurred:', error);
    }
}
A try-catch block that simulates a user with insufficient permissions. An error is caught and differentiated to check if it is a PermissionDeniedError, and the appropriate action is taken.