{"id":41214956,"url":"https://github.com/phore/phore-service-exception","last_synced_at":"2026-01-22T23:58:44.999Z","repository":{"id":56873316,"uuid":"152563857","full_name":"phore/phore-service-exception","owner":"phore","description":null,"archived":false,"fork":false,"pushed_at":"2022-08-20T06:53:28.000Z","size":2,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-05-18T19:22:18.392Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/phore.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-11T09:13:52.000Z","updated_at":"2022-08-20T06:53:31.000Z","dependencies_parsed_at":"2022-08-20T22:31:11.495Z","dependency_job_id":null,"html_url":"https://github.com/phore/phore-service-exception","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/phore/phore-service-exception","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phore%2Fphore-service-exception","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phore%2Fphore-service-exception/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phore%2Fphore-service-exception/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phore%2Fphore-service-exception/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/phore","download_url":"https://codeload.github.com/phore/phore-service-exception/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/phore%2Fphore-service-exception/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28675279,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-22T20:48:19.482Z","status":"ssl_error","status_checked_at":"2026-01-22T20:48:14.968Z","response_time":144,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-01-22T23:58:43.031Z","updated_at":"2026-01-22T23:58:44.989Z","avatar_url":"https://github.com/phore.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n\nServiceException and ServiceExceptionKernel\n\nA PHP 8 library for standardized exception handling in microservices architectures. This library provides:\n\n    ServiceException: A custom exception class that encapsulates error information in a consistent, serializable format, suitable for API responses and inter-service communication.\n    ServiceExceptionKernel: A helper class that centralizes exception creation, handling, and contextual information like service names and trace IDs.\n\nTable of Contents\n\n    Features\n    Installation\n    Usage\n        Initialization\n        Creating and Throwing Exceptions\n        Catching and Handling Exceptions\n        Generating API Responses\n        Logging Exceptions\n    Classes\n        ServiceException\n            Properties\n            Methods\n        ServiceExceptionKernel\n            Methods\n    Best Practices\n        Handling Sensitive Information\n        Environment Configuration\n    Examples\n        Example 1: Basic Usage\n        Example 2: Handling Nested Exceptions\n        Example 3: Custom Exception Types\n    Contributing\n    License\n\nFeatures\n\n    Standardized error format for API responses.\n    Supports nested exceptions (inner_error) for detailed error chains.\n    Includes HTTP status codes for appropriate client responses.\n    Controls the level of detail in error responses based on environment and detail level.\n    Manages sensitive information to prevent exposure in production environments.\n    Facilitates distributed tracing with trace IDs.\n    Simplifies exception handling with the ServiceExceptionKernel.\n\nInstallation\n\nUse Composer to install the library (assuming it's available via Composer):\n\nbash\n\ncomposer require yournamespace/service-exception\n\nUsage\nInitialization\n\nAt the entry point of your application (e.g., in a middleware or base controller), initialize the ServiceExceptionKernel:\n\nphp\n\nuse YourNamespace\\ServiceExceptionKernel;\n\n$environment = getenv('APP_ENV') ?: 'production';\n$serviceName = 'UserService';\n$traceId = $_SERVER['HTTP_X_TRACE_ID'] ?? null;\n\n$exceptionKernel = new ServiceExceptionKernel(\nserviceName: $serviceName,\nenvironment: $environment,\ntraceId: $traceId,\ndefaultHttpStatusCode: 500,\ndetailLevel: ($environment === 'production') ? 0 : 2\n);\n\nCreating and Throwing Exceptions\n\nUse the ServiceExceptionKernel to create and throw exceptions consistently:\n\nphp\n\ntry {\n// Some code that may throw an exception\n$user = $userService-\u003egetUserById($userId);\nif (!$user) {\nthrow $exceptionKernel-\u003ecreateException(\nerrorCode: 'USER_NOT_FOUND',\nmessage: \"User with ID {$userId} not found.\",\nhttpStatusCode: 404,\ndetails: ['userId' =\u003e $userId]\n);\n}\n} catch (Throwable $e) {\n// Handle the exception\n}\n\nCatching and Handling Exceptions\n\nCatch exceptions and convert them using the kernel:\n\nphp\n\ntry {\n// Code that may throw exceptions\n} catch (Throwable $e) {\n$serviceException = $exceptionKernel-\u003ehandleException($e);\n// Further handling...\n}\n\nGenerating API Responses\n\nUse the toApiResponse method of ServiceException to generate standardized error responses:\n\nphp\n\n$responseData = $serviceException-\u003etoApiResponse(\ndetailLevel: $exceptionKernel-\u003egetDetailLevel(),\nenvironment: $exceptionKernel-\u003egetEnvironment()\n);\n\n// Return HTTP response (using your framework's response class)\nreturn new JsonResponse($responseData, $serviceException-\u003egetHttpStatusCode());\n\nLogging Exceptions\n\nLog exceptions using a PSR-3 compliant logger:\n\nphp\n\nuse Psr\\Log\\LoggerInterface;\n\n// Assuming $logger is an instance of LoggerInterface\n$exceptionKernel-\u003elogException($serviceException, $logger);\n\nClasses\nServiceException\n\nA custom exception class that extends PHP's Exception and implements JsonSerializable.\nProperties\n\n    errorCode (string): Custom error code.\n    message (string): Error message.\n    service (string): Name of the service where the error occurred.\n    httpStatusCode (int): HTTP status code associated with the error.\n    timestamp (string): Timestamp when the error occurred (ISO 8601 format).\n    traceId (string|null): Trace ID for distributed tracing.\n    exceptionType (string|null): Type of the exception.\n    details (array|null): Additional error details.\n    innerError (ServiceException|null): Nested inner exception.\n    stackTrace (array): Stack trace of the exception.\n\nMethods\n\n    __construct(...): Initializes a new instance of ServiceException.\n    fromJson(string $json, bool $strict = false): ?ServiceException: Creates an instance from a JSON string.\n    fromArray(array $data, bool $strict = false): ?ServiceException: Creates an instance from an array.\n    fromException(Exception|\\Error $error, string $service, int $httpStatusCode = 500): ServiceException: Creates an instance from an existing exception.\n    jsonSerialize(): array: Specifies data for JSON serialization.\n    __toString(): string: Returns a string representation of the exception.\n    toApiResponse(int $detailLevel = 0, string $environment = 'production'): array: Converts the exception to a format suitable for API responses.\n    getters: Various getters for accessing properties.\n\nServiceExceptionKernel\n\nA helper class that centralizes exception creation, handling, and contextual information.\nMethods\n\n    __construct(...): Initializes the kernel with service name, environment, etc.\n    createException(...): Creates a ServiceException with provided information.\n    fromThrowable(Throwable $throwable, ?int $httpStatusCode = null): ServiceException: Converts any Throwable into a ServiceException.\n    handleException(Throwable $throwable): ServiceException: Handles an exception and converts it.\n    logException(ServiceException $exception, LoggerInterface $logger): void: Logs the exception.\n    generateTraceId(): string: Generates a unique trace ID.\n    getters and setters: Access and modify properties like trace ID, environment, detail level, etc.\n\nBest Practices\nHandling Sensitive Information\n\n    Production Environment: Use minimal detail level (0) to avoid exposing sensitive information.\n    Development Environment: Higher detail levels (1 or 2) can be used to aid debugging.\n    Redaction: Implement logic to redact or exclude sensitive fields from error responses.\n    Logging: Log full exception details internally for debugging purposes.\n\nEnvironment Configuration\n\n    Environment Variables: Use environment variables to set the application environment (APP_ENV).\n    Central Configuration: Configure default HTTP status codes and detail levels in one place.\n\nExamples\nExample 1: Basic Usage\n\nphp\n\nuse YourNamespace\\ServiceExceptionKernel;\n\n$exceptionKernel = new ServiceExceptionKernel('UserService', 'production');\n\ntry {\n// Some code that throws an exception\nthrow new \\RuntimeException('An unexpected error occurred.');\n} catch (Throwable $e) {\n$serviceException = $exceptionKernel-\u003ehandleException($e);\n$responseData = $serviceException-\u003etoApiResponse(\ndetailLevel: $exceptionKernel-\u003egetDetailLevel(),\nenvironment: $exceptionKernel-\u003egetEnvironment()\n);\nreturn new JsonResponse($responseData, $serviceException-\u003egetHttpStatusCode());\n}\n\nExample 2: Handling Nested Exceptions\n\nphp\n\nuse YourNamespace\\ServiceExceptionKernel;\n\n$exceptionKernel = new ServiceExceptionKernel('OrderService', 'development');\n\ntry {\n// Code that may throw exceptions\ntry {\n// Some code that throws an exception\nthrow new \\InvalidArgumentException('Invalid order ID.');\n} catch (\\InvalidArgumentException $e) {\nthrow $exceptionKernel-\u003ecreateException(\nerrorCode: 'INVALID_ORDER_ID',\nmessage: 'The provided order ID is invalid.',\nhttpStatusCode: 400,\nexceptionType: 'InvalidOrderIdException',\ninnerError: $exceptionKernel-\u003efromThrowable($e)\n);\n}\n} catch (Throwable $e) {\n$serviceException = $exceptionKernel-\u003ehandleException($e);\n$responseData = $serviceException-\u003etoApiResponse(\ndetailLevel: $exceptionKernel-\u003egetDetailLevel(),\nenvironment: $exceptionKernel-\u003egetEnvironment()\n);\nreturn new JsonResponse($responseData, $serviceException-\u003egetHttpStatusCode());\n}\n\nExample 3: Custom Exception Types\n\nphp\n\nuse YourNamespace\\ServiceException;\n\nclass NotFoundException extends ServiceException\n{\npublic function __construct(\nstring $errorCode,\nstring $message,\nstring $service,\n?string $traceId = null,\n?array $details = null,\n?ServiceException $innerError = null\n) {\nparent::__construct(\nerrorCode: $errorCode,\nmessage: $message,\nservice: $service,\nhttpStatusCode: 404,\ntraceId: $traceId,\nexceptionType: 'NotFoundException',\ndetails: $details,\ninnerError: $innerError\n);\n}\n}\n\n// Usage\nthrow new NotFoundException(\nerrorCode: 'USER_NOT_FOUND',\nmessage: 'The user with ID 12345 was not found.',\nservice: 'UserService',\ndetails: ['userId' =\u003e 12345]\n);\n\nContributing\n\nContributions are welcome! Please submit a pull request or open an issue to discuss improvements, bug fixes, or new features.\nLicense\n\nThis project is licensed under the MIT License. See the LICENSE file for details.\n\nNote: Replace YourNamespace with the appropriate namespace for your project. Ensure that all dependencies are properly installed and autoloaded via Composer.\n\nFeel free to reach out if you have any questions or need further assistance!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphore%2Fphore-service-exception","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fphore%2Fphore-service-exception","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphore%2Fphore-service-exception/lists"}