VOOZH about

URL: https://deepwiki.com/hypervel/auth/7-exception-handling

⇱ Exception Handling | hypervel/auth | DeepWiki


Loading...
Menu

Exception Handling

Purpose and Scope

This document provides a comprehensive guide to exception handling in the hypervel/auth package. The package uses two primary exception classes to handle authentication and authorization failures: AuthenticationException for identity verification failures and AuthorizationException for permission check failures. These exceptions are thrown by middleware components and can be caught by exception handlers to generate appropriate HTTP responses.

For detailed information about individual exception classes, see AuthenticationException and AuthorizationException. For information about the middleware that throws these exceptions, see Authenticate Middleware and Authorize Middleware.

Sources: src/AuthenticationException.php1-75 src/Access/AuthorizationException.php1-91


Exception Architecture Overview

The exception handling system in hypervel/auth follows a two-tier model that mirrors the authentication/authorization separation in the overall architecture:

Exception ClassPurposeThrown ByDefault HTTP StatusConfigurable
AuthenticationExceptionUser identity verification failedAuthenticate middleware401 or redirectRedirect path
AuthorizationExceptionUser lacks permission for actionAuthorize middleware, Gate403 (or 404)HTTP status code

Both exception classes extend PHP's base Exception class and provide additional context-specific functionality for their respective authentication or authorization failures.

Sources: src/AuthenticationException.php10-75 src/Access/AuthorizationException.php10-91


Exception Flow in Request Pipeline

The following diagram illustrates how exceptions propagate through the request pipeline and are converted into HTTP responses:


Sources: src/AuthenticationException.php34-40 src/Access/AuthorizationException.php25-30


AuthenticationException Details

The AuthenticationException class is thrown when a user cannot be authenticated. It tracks which guards were checked and provides redirect capabilities for web applications.

Key Properties

- $guards: array - List of guard names that failed authentication
- $redirectTo: ?string - Explicit redirect path
- $redirectToCallback: ?callable - Static callback for dynamic redirect generation

Constructor Signature

The exception is created with three optional parameters: src/AuthenticationException.php34-40

  1. message - Error message (default: "Unauthenticated.")
  2. guards - Array of guard names that were checked
  3. redirectTo - Optional explicit redirect path

Guard Context

When authentication fails, the exception stores which guards were checked. This allows exception handlers to provide context-aware responses. For example, if JWT and session guards both failed, the handler knows no authentication method succeeded.

Method: guards()
Returns: array of guard names
Location: <FileRef file-url="https://github.com/hypervel/auth/blob/b9187f7a/src/AuthenticationException.php#L47-L50" min=47 max=50 file-path="src/AuthenticationException.php">Hii</FileRef>

Redirect Handling

The exception provides flexible redirect capabilities for web applications:

Explicit Redirect: Set directly in constructor via $redirectTo parameter src/AuthenticationException.php39

Dynamic Redirect: Configure a static callback using redirectUsing() src/AuthenticationException.php71-74

Resolution: The redirectTo() method resolves the redirect path in order of precedence src/AuthenticationException.php55-66:

  1. Explicit $redirectTo value
  2. Result from static $redirectToCallback
  3. null if neither is configured

This design allows applications to configure redirect logic globally while still supporting per-exception overrides.

Sources: src/AuthenticationException.php1-75


AuthorizationException Details

The AuthorizationException class is thrown when an authenticated user lacks permission to perform an action. It integrates with the Response class to carry detailed authorization context.

Key Properties

- $response: ?Response - The Gate Response object with denial details
- $status: ?int - HTTP status code override (defaults to 403)
- $code: int|string - Application-specific error code

Constructor Signature

The exception constructor accepts three optional parameters: src/Access/AuthorizationException.php25-30

  1. message - Error message (default: "This action is unauthorized.")
  2. code - Application-specific error code
  3. previous - Previous exception for chaining

Response Integration

The exception can carry a Response object that contains detailed authorization context including the denial message, error code, and any custom metadata: src/Access/AuthorizationException.php35-48

Method: response()
Returns: ?Response
Purpose: Retrieve the Gate Response object

Method: setResponse(?Response $response)
Returns: static
Purpose: Attach a Response object for context

HTTP Status Code Management

The exception supports flexible HTTP status code configuration:

Default Behavior: Returns 403 Forbidden if no status is explicitly set

Custom Status: Use withStatus(?int $status) to set any status code src/Access/AuthorizationException.php53-58

404 Shortcut: Use asNotFound() to set status to 404, hiding resource existence src/Access/AuthorizationException.php63-66

Status Checking: Use hasStatus() to determine if a custom status was set src/Access/AuthorizationException.php71-74

Status Retrieval: Use status() to get the configured status code src/Access/AuthorizationException.php79-82

Response Conversion

The exception can convert itself into a Response object via the toResponse() method src/Access/AuthorizationException.php87-90 This method creates a denial response using the exception's message and code, then applies the configured HTTP status.

Sources: src/Access/AuthorizationException.php1-91


Exception Usage in Middleware

The following diagram maps exception creation and throwing within the middleware components:


Sources: src/AuthenticationException.php34-40 src/Access/AuthorizationException.php25-30 src/Access/AuthorizationException.php43-90


Exception Handling Patterns

Pattern 1: Authentication Redirect for Web Applications

When handling AuthenticationException in web applications, check for a configured redirect path and send a 302 redirect response instead of a 401 error:

1. Catch AuthenticationException
2. Call $exception->redirectTo($request)
3. If result is not null, return redirect response
4. Otherwise, return 401 JSON response for API clients

The redirect path can be configured statically using AuthenticationException::redirectUsing() with a callback that receives the request and returns a path src/AuthenticationException.php71-74

Pattern 2: Authorization Status Code Customization

When handling AuthorizationException, check if a custom HTTP status was set:

1. Catch AuthorizationException
2. Call $exception->hasStatus()
3. If true, use $exception->status() as HTTP status code
4. If false, default to 403

This pattern allows policies and gate checks to hide resource existence by using 404 instead of 403 src/Access/AuthorizationException.php63-66

Pattern 3: Response Context Extraction

Extract detailed authorization context from the exception's attached Response object:

1. Catch AuthorizationException
2. Call $exception->response()
3. If not null, extract message, code, and metadata from Response
4. Use toResponse() to convert exception to Response object

The Response object contains the original denial message and any application-specific error codes src/Access/AuthorizationException.php35-38 src/Access/AuthorizationException.php87-90

Sources: src/AuthenticationException.php55-74 src/Access/AuthorizationException.php63-90


Exception Class Hierarchy

The following diagram shows the class relationships and key methods for both exception types:


Sources: src/AuthenticationException.php10-75 src/Access/AuthorizationException.php10-91


Integration with Gate System

The Gate class creates and throws AuthorizationException when authorization checks fail. The gate attaches its Response object to the exception to preserve denial context:


The gate does not set HTTP status codes directly - that responsibility falls to the middleware or exception handlers based on the context. Policies can influence status codes by using Response::deny()->withStatus() or Response::denyAsNotFound() when creating denial responses.

Sources: src/Access/AuthorizationException.php43-48 src/Access/AuthorizationException.php87-90


Best Practices

For Application Developers

  1. Configure Redirects Globally: Use AuthenticationException::redirectUsing() in application bootstrap to set a global redirect callback rather than catching exceptions in multiple places

  2. Use asNotFound() Strategically: Call asNotFound() on authorization exceptions when denying access to resources that should appear non-existent to unauthorized users

  3. Preserve Exception Context: When catching authorization exceptions, always check for an attached Response object to preserve denial messages and codes

  4. Handle Both Exception Types: Implement exception handlers that differentiate between authentication (identity) and authorization (permission) failures

For Guard Implementers

  1. Specify Guard Names: When creating AuthenticationException, always pass the guard name(s) that failed authentication to provide context

  2. Throw Consistently: Throw AuthenticationException for any authentication failure, not alternative exceptions

For Policy Writers

  1. Use Response Objects: Return Response::deny() with meaningful messages instead of plain boolean false

  2. Set Status Codes When Needed: Use Response::denyAsNotFound() or Response::deny()->withStatus(404) when resource existence should be hidden

Sources: src/AuthenticationException.php34-74 src/Access/AuthorizationException.php63-90