Skip to content

Commit bdcf763

Browse files
Merge pull request #4 from MaplePHP/develop
v1.2.0
2 parents d1a6978 + 7755ea9 commit bdcf763

16 files changed

+484
-120
lines changed

README.md

Lines changed: 126 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,16 @@
22

33
![Screen dump on how blunder looks like](https://wazabii.se/github-assets/maplephp-blunder.png "MaplePHP Blunder")
44

5-
**Blunder is a designed error handling framework for PHP.** It provides a pretty, user-friendly interface that simplifies debugging with excellent memory management. Blunder offers various handlers, including HTML, JSON, XML, plain text, and silent modes, allowing flexible error presentation. Seamlessly integrating with tools like the PSR-7 and PSR-3 compliant MaplePHP Log library, Blunder is an excellent choice for managing errors in PHP applications, helping users easily identify and resolve issues.
5+
**Blunder is a pretty error handling framework for PHP.** It provides a pretty, user-friendly interface that simplifies
6+
debugging with excellent memory management. Blunder offers various handlers, including HTML, JSON, XML, CLI, plain text,
7+
and silent modes, allowing flexible error presentation. Seamlessly integrating with tools like the PSR-7 and PSR-3
8+
compliant MaplePHP Log library, Blunder is an excellent choice for managing errors in PHP applications, helping users easily
9+
identify and resolve issues.
10+
11+
With Blunder, you can easily control how errors are handled—whether you want to suppress specific severities, redirect them to
12+
logging, or assign them to different handlers. For example, you can automatically log all Deprecated warnings while keeping
13+
Warnings visible for debugging. This level of customization ensures a smooth and efficient error-handling experience tailored
14+
to your needs.
615

716
## Installation
817
Installation with composer
@@ -36,19 +45,106 @@ All handlers utilize the namespace `MaplePHP\Blunder\Handlers\[TheHandlerName]`.
3645
* **SilentHandler**: Suppresses error output but can log errors to files. You can choose to output fatal errors if necessary.
3746

3847

39-
## Exclude severities
40-
You can exclude/remove severities from the error handler.
48+
## Excluding Specific Error Severities from the Handler
49+
50+
With Blunder, you can exclude specific error severities from the handler. This allows you to control how certain errors are processed without affecting the overall error handling behavior.
51+
52+
### 1. Exclude Severity Levels
53+
This method removes the specified severities from Blunder’s handler, allowing them to be processed by PHP’s default error reporting.
4154

4255
```php
4356
$run = new Run(new HtmlHandler());
4457
$run->severity()->excludeSeverityLevels([E_DEPRECATED, E_USER_DEPRECATED]);
4558
$run->load();
4659
```
47-
*[You can find a list of available severities here](https://www.php.net/manual/en/errorfunc.constants.php)*
60+
**Effect:**
61+
- `E_DEPRECATED` and `E_USER_DEPRECATED` will no longer be handled by Blunder.
62+
- PHP’s default error handling will take over for these severities.
63+
64+
---
65+
66+
### 2. Exclude and Redirect Severities
67+
Instead of letting PHP handle the excluded severities, you can redirect them to a custom function for further processing, such as logging.
68+
69+
#### **Behavior:**
70+
- **`return true;`** → Completely suppresses errors of the excluded severities.
71+
- **`return false;`** → Uses PHP’s default error handler for the excluded severities.
72+
- **`return null|void;`** → Keeps using Blunder’s error handler as usual.
73+
74+
```php
75+
$run = new Run(new HtmlHandler());
76+
$run->severity()
77+
->excludeSeverityLevels([E_WARNING, E_USER_WARNING])
78+
->redirectTo(function ($errNo, $errStr, $errFile, $errLine) {
79+
error_log("Custom log: $errStr in $errFile on line $errLine");
80+
return true; // Suppresses output for excluded severities
81+
});
82+
```
83+
84+
**Example Use Case:**
85+
- Log warnings instead of displaying them.
86+
- Ensure deprecated notices are logged but not shown in production.
87+
88+
---
89+
90+
### 3. Redirect Excluded Severities to a New Handler
91+
You can also redirect excluded severities to a completely different error handler.
92+
93+
```php
94+
$run = new Run($errorHandler);
95+
$run->severity()
96+
->excludeSeverityLevels([E_WARNING, E_USER_WARNING])
97+
->redirectTo(function ($errNo, $errStr, $errFile, $errLine) {
98+
return new JsonHandler();
99+
});
100+
```
101+
**Effect:**
102+
- `E_WARNING` and `E_USER_WARNING` will be processed by `JsonHandler` instead of `HtmlHandler` or PHP’s default error handling.
103+
104+
---
105+
106+
**Note:**
107+
You can find a full list of available PHP error severities [here](https://www.php.net/manual/en/errorfunc.constants.php).
108+
109+
---
110+
111+
## Enabling or Disabling Trace Lines
112+
This allows you to control the level of detail shown in error messages based on your debugging needs.
113+
You can customize this behavior using the configuration:
114+
115+
```php
116+
$handler = new CliHandler();
117+
118+
// Enable or disable trace lines
119+
$handler->enableTraceLines(true); // Set false to disable
120+
121+
$run = new Run($handler);
122+
$run->load();
123+
```
124+
125+
### **Options:**
126+
- `true` → Enables trace lines (default in all cases except for in the CliHandler).
127+
- `false` → Disables trace lines, making error messages cleaner.
128+
129+
This allows you to control the level of detail shown in error messages based on your debugging needs.
130+
131+
## Remove location headers
132+
This will remove location headers and make sure that no PHP redirect above this code will execute.
133+
```php
134+
$run = new Run(new HtmlHandler());
135+
$run->removeLocationHeader(true);
136+
$run->load();
137+
```
48138

49-
## Advanced Usage
139+
## Setting the Exit Code for Errors
140+
To make Blunder trigger a specific exit code when an error occurs. This is useful in unit testing and CI/CD, ensuring tests fail on errors.
141+
```php
142+
$run = new Run(new CliHandler());
143+
$run->setExitCode(1);
144+
$run->load();
145+
```
50146

51-
### Event Handling
147+
## Event Handling
52148

53149
You can use Blunder's **event** functionality to handle errors, such as logging them to a file. The example below shows how to display a pretty error page in development mode and log errors in production.
54150

@@ -101,11 +197,34 @@ $run->event(function($item, $http) use($production) {
101197
$run->load();
102198
```
103199

104-
### HTTP Messaging
200+
## HTTP Messaging
105201

106202
The Blunder `Run` class can take two arguments. The first argument is required and should be a class handler (`HandlerInterface`). The second argument is optional and expects an HTTP message class used to pass an already open PSR-7 response and `ServerRequest` instance instead of creating a new one for better performance.
107203

108204
```php
109205
// $run = new Run(HandlerInterface, HttpMessagingInterface(ResponseInterface, ServerRequestInterface));
110206
$run = new Run(new HtmlHandler(), new HttpMessaging($response, $request));
207+
```
208+
209+
## Exception Chaining
210+
When rethrowing an exception with a different type, PHP resets the file and line number to the location of the new `throw` statement. This can make debugging harder, as the error message will point to the wrong file instead of the original source of the exception.
211+
212+
To preserve the original exception’s file and line number while changing its type, you can use the **`preserveExceptionOrigin`** method provided by Blunder.
213+
214+
#### Example: Preserving the Original Exception’s Location
215+
```php
216+
try {
217+
// An exception has been triggered inside dispatch()
218+
$dispatch = $row->dispatch();
219+
} catch (Throwable $e) {
220+
// By default, rethrowing with a new exception class changes the error location
221+
$exception = new RuntimeException($e->getMessage(), (int) $e->getCode());
222+
223+
// Preserve the original exception's file and line number
224+
if (method_exists($e, "preserveExceptionOrigin")) {
225+
$e->preserveExceptionOrigin($exception);
226+
}
227+
228+
throw $exception;
229+
}
111230
```

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "maplephp/blunder",
33
"type": "library",
4-
"version": "v1.1.2",
4+
"version": "v1.2.0",
55
"description": "Blunder is a well-designed PHP error handling framework.",
66
"keywords": [
77
"php",

src/BlunderErrorException.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
3+
namespace MaplePHP\Blunder;
4+
5+
use Exception;
6+
use ErrorException;
7+
use ReflectionClass;
8+
use Throwable;
9+
10+
class BlunderErrorException extends ErrorException
11+
{
12+
protected ?string $prettyMessage = null;
13+
14+
/**
15+
* Will return the default ErrorException message
16+
*
17+
* @return string|null
18+
*/
19+
public function getPrettyMessage(): ?string
20+
{
21+
return (!is_null($this->prettyMessage)) ? $this->prettyMessage : $this->message;
22+
}
23+
24+
/**
25+
* Set pretty message that can be used in execption handlers
26+
*
27+
* @param string $message
28+
* @return void
29+
*/
30+
public function setPrettyMessage(string $message): void
31+
{
32+
$this->prettyMessage = $message;
33+
}
34+
35+
/**
36+
* Preserves the original exception's file and line number
37+
* when rethrowing with a different exception type.
38+
*
39+
* @param Exception $exception The new exception instance that will receive the original file and line number.
40+
* @return void
41+
*/
42+
public function preserveExceptionOrigin(Throwable $exception): void
43+
{
44+
$reflection = new ReflectionClass(Exception::class);
45+
$fileProp = $reflection->getProperty('file');
46+
$fileProp->setValue($exception, $this->getFile());
47+
$lineProp = $reflection->getProperty('line');
48+
$lineProp->setValue($exception, $this->getLine());
49+
}
50+
}

0 commit comments

Comments
 (0)