VOOZH about

URL: https://deepwiki.com/hypervel/foundation/4.4-exception-handling-and-error-responses

⇱ Exception Handling and Error Responses | hypervel/foundation | DeepWiki


Loading...
Last indexed: 7 February 2026 (101eff)
Menu

Exception Handling and Error Responses

This document covers the exception handling system in Hypervel Foundation, which manages how exceptions are reported (logged) and rendered into HTTP responses. The system provides customization points for application-specific exception handling while offering sensible defaults for common exception types.

For information about Form Request validation exceptions, see 4.3. For HTTP kernel integration, see 4.1.


Overview

The exception handling system is centered on the Handler class located at src/Exceptions/Handler.php This class extends Hyperf's ExceptionHandler and implements the ExceptionHandlerContract interface src/Exceptions/Contracts/ExceptionHandler.php

The handler performs two primary functions:

  1. Reporting: Logging exceptions with appropriate context and log levels
  2. Rendering: Converting exceptions into HTTP responses (JSON or HTML)

Sources: src/Exceptions/Handler.php47-878 src/Exceptions/Contracts/ExceptionHandler.php1-37


Exception Handler Architecture


Handler Composition

The Handler class contains multiple arrays that control its behavior:

PropertyTypePurpose
dontReportarrayUser-defined exception types that should not be reported
internalDontReportarrayFramework exception types that should not be reported
reportCallbacksReportableHandler[]Custom reporting callbacks registered via reportable()
renderCallbacksClosure[]Custom rendering callbacks registered via renderable()
exceptionMaparrayMaps exception types to transformation functions
contextCallbacksarrayCallbacks that build logging context
levelsarrayMaps exception types to PSR log levels
dontFlasharrayInput keys that should never be flashed to session

Sources: src/Exceptions/Handler.php52-129 src/Exceptions/Handler.php136-141


Exception Reporting Flow


Reporting Process Details

The reporting process follows this sequence src/Exceptions/Handler.php264-315:

  1. Exception Mapping: The exception is mapped using mapException() to potentially transform it into another exception type
  2. Duplicate Check: If withoutDuplicates is enabled, duplicate exceptions are filtered
  3. Don't Report Check: Exceptions implementing ShouldntReport or in the dontReport/internalDontReport arrays are skipped
  4. Custom Report Method: If the exception has a report() method, it's called first
  5. Report Callbacks: Registered reportCallbacks are executed in order
  6. Logging: If not stopped by custom handlers, the exception is logged with the configured log level

Internal Don't Report List

The following exception types are never reported by default src/Exceptions/Handler.php110-118:

  • AuthenticationException::class
  • AuthorizationException::class
  • HyperfHttpException::class
  • HttpResponseException::class
  • ModelNotFoundException::class
  • TokenMismatchException::class
  • ValidationException::class

Sources: src/Exceptions/Handler.php264-315 src/Exceptions/Handler.php348-365 src/Exceptions/Handler.php110-118


Exception Rendering Flow


Rendering Process Details

The rendering flow src/Exceptions/Handler.php426-450 follows this priority:

  1. Custom render() Method: If the exception has a render() method, it's called first
  2. Responsable Interface: If the exception implements Responsable, toResponse() is called
  3. Exception Preparation: prepareException() transforms certain exceptions:
    • ModelNotFoundExceptionNotFoundHttpException
    • AuthorizationExceptionHttpException or AccessDeniedHttpException
  4. Render Callbacks: Custom renderCallbacks are checked for matching exception types
  5. Type-Specific Handling: Built-in handling for common exception types
  6. Default Rendering: Falls back to renderExceptionResponse()

Sources: src/Exceptions/Handler.php426-450 src/Exceptions/Handler.php767-780


Response Format Selection


JSON vs HTML Decision

The handler uses shouldReturnJson() src/Exceptions/Handler.php649-654 to determine response format:

  1. Custom Callback: If shouldRenderJsonWhenCallback is set, it's called
  2. Request Expectation: Otherwise, checks $request->expectsJson()

JSON Response Structure

When debug mode is enabled src/Exceptions/Handler.php827-832:


When debug mode is disabled src/Exceptions/Handler.php833-835:


Error View Resolution

For HTTP exceptions, the handler looks for views in this order src/Exceptions/Handler.php793-808:

  1. errors::{statusCode} (e.g., errors::404)
  2. errors::{statusCode}xx (e.g., errors::4xx)
  3. Falls back to HTML rendering if no view exists

Sources: src/Exceptions/Handler.php516-521 src/Exceptions/Handler.php649-654 src/Exceptions/Handler.php825-836 src/Exceptions/Handler.php793-808


Customization Mechanisms

Registering Report Callbacks

The reportable() method registers custom reporting logic src/Exceptions/Handler.php153-162:


Returns a ReportableHandler that allows conditional reporting via stop() method.

Registering Render Callbacks

The renderable() method registers custom rendering logic src/Exceptions/Handler.php167-176:


The callback receives the exception and request, and should return a ResponseInterface or null.

Exception Mapping

The map() method transforms exceptions src/Exceptions/Handler.php181-194:


Usage patterns:

  • map(ExceptionA::class, ExceptionB::class) - Simple class replacement
  • map(ExceptionA::class, fn($e) => new ExceptionB('', 0, $e)) - Custom transformation
  • map(fn(ExceptionA $e) => new ExceptionB()) - Closure with type hint

Context Building

The buildContextUsing() method adds custom context to log entries src/Exceptions/Handler.php414-419:


Default Context src/Exceptions/Handler.php400-409:

  • userId: The authenticated user's ID (if available)
  • exception: The exception instance
  • Any context from the exception's context() method

Log Level Configuration

The level() method sets custom log levels for exception types src/Exceptions/Handler.php252-257:


Accepts PSR log levels: LogLevel::EMERGENCY, LogLevel::ERROR, etc.

Sources: src/Exceptions/Handler.php153-162 src/Exceptions/Handler.php167-176 src/Exceptions/Handler.php181-194 src/Exceptions/Handler.php414-419 src/Exceptions/Handler.php252-257


Special Exception Handling

Validation Exceptions


Validation Exception Handling

For JSON responses src/Exceptions/Handler.php638-644:

  • Returns status code from $exception->status
  • Includes message and errors array

For HTML responses src/Exceptions/Handler.php567-577:

  • Flashes errors to session under the specified error bag
  • Flashes input except fields in dontFlash array
  • Redirects to $exception->redirectTo or previous URL

Don't Flash Fields src/Exceptions/Handler.php125-129:

  • current_password
  • password
  • password_confirmation

Sources: src/Exceptions/Handler.php557-644 src/Exceptions/Handler.php582-603 src/Exceptions/Handler.php125-129

Authentication Exceptions


Authentication Exception Handling src/Exceptions/Handler.php547-552:

  • JSON: Returns 401 with message
  • HTML: Redirects to $exception->redirectTo($request) or the login route

Sources: src/Exceptions/Handler.php547-552

Authorization Exceptions

Authorization exceptions are transformed during prepareException() src/Exceptions/Handler.php771-777:

ConditionTransformation
AuthorizationException with statusHttpException with that status code
AuthorizationException without statusAccessDeniedHttpException (403)

Sources: src/Exceptions/Handler.php767-780

Model Not Found Exceptions

ModelNotFoundException is transformed to NotFoundHttpException src/Exceptions/Handler.php770 which results in a 404 response.

Sources: src/Exceptions/Handler.php767-780


Advanced Features

Duplicate Exception Prevention

The dontReportDuplicates() method enables duplicate detection src/Exceptions/Handler.php841-846:


When enabled, the handler tracks reported exceptions in the coroutine context src/Exceptions/Handler.php317-335 using:

  • Context key: __errors.reportedExceptions
  • Stores array of reported exception instances

After Response Callbacks

The afterResponse() method registers callbacks executed after response rendering src/Exceptions/Handler.php526-534:


Callbacks receive: ($response, $exception, $request)

Stored in coroutine context: __errors.handler.afterResponse

Custom Response Finalization

The respondUsing() method sets a custom response finalizer src/Exceptions/Handler.php757-762:


The callback receives ($response, $exception, $request) and must return a ResponseInterface.

Ignore Configuration Methods

MethodPurpose
ignore($exceptions)Add exception types to don't report list src/Exceptions/Handler.php209-216
dontReport($exceptions)Alias of ignore() src/Exceptions/Handler.php201-204
stopIgnoring($exceptions)Remove exception types from both don't report lists src/Exceptions/Handler.php233-244
dontFlash($attributes)Add input keys to don't flash list src/Exceptions/Handler.php221-228

Sources: src/Exceptions/Handler.php841-846 src/Exceptions/Handler.php317-335 src/Exceptions/Handler.php526-534 src/Exceptions/Handler.php757-762 src/Exceptions/Handler.php201-244


Integration with Hyperf

Hyperf ExceptionHandler Interface

The Handler class implements two methods required by Hyperf src/Exceptions/Handler.php864-878:


  • Calls report() to log the exception
  • Calls render() to generate response
  • Returns the final response

  • Always returns true to handle all exceptions

Request Resolution

The handler retrieves the current request from the container src/Exceptions/Handler.php869-870:


This relies on the HTTP kernel binding the request to the container during request handling.

Sources: src/Exceptions/Handler.php864-878


Error Rendering Services

Exception Renderer Contract

The ExceptionRenderer interface provides custom exception rendering src/Exceptions/Handler.php709-711:


This allows applications to register custom debug screens (e.g., Whoops, Ignition).

HTML Error Renderer

The HtmlErrorRenderer class provides fallback HTML rendering src/Exceptions/Handler.php724-726:


This service renders exceptions using Symfony's error rendering component.

Error View Registration

The RegisterErrorViewPaths bootstrapper src/Exceptions/Handler.php785-788 is called during handler construction to register error view paths:


Sources: src/Exceptions/Handler.php705-726 src/Exceptions/Handler.php785-788


Exception Handler Contract

The ExceptionHandlerContract interface defines the public API src/Exceptions/Contracts/ExceptionHandler.php11-36:

MethodPurpose
report(Throwable $e): voidReport or log an exception
shouldReport(Throwable $e): boolDetermine if exception should be reported
render(Request $request, Throwable $e): ResponseInterfaceRender exception into HTTP response
afterResponse(callable $callback): voidRegister callback for after response rendering

This contract provides a stable API for custom exception handlers and testing.

Sources: src/Exceptions/Contracts/ExceptionHandler.php1-37