Skip to content

Commit 20a8638

Browse files
committed
Add redirect removed severity
1 parent c5d2b2f commit 20a8638

15 files changed

+478
-119
lines changed

README.md

Lines changed: 121 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
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 designed 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.
610

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

3842

39-
## Exclude severities
40-
You can exclude/remove severities from the error handler.
43+
## Excluding Specific Error Severities from the Handler
44+
45+
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.
46+
47+
### 1. Exclude Severity Levels
48+
This method removes the specified severities from Blunder’s handler, allowing them to be processed by PHP’s default error reporting.
4149

4250
```php
4351
$run = new Run(new HtmlHandler());
4452
$run->severity()->excludeSeverityLevels([E_DEPRECATED, E_USER_DEPRECATED]);
4553
$run->load();
4654
```
47-
*[You can find a list of available severities here](https://www.php.net/manual/en/errorfunc.constants.php)*
55+
**Effect:**
56+
- `E_DEPRECATED` and `E_USER_DEPRECATED` will no longer be handled by Blunder.
57+
- PHP’s default error handling will take over for these severities.
58+
59+
---
60+
61+
### 2. Exclude and Redirect Severities
62+
Instead of letting PHP handle the excluded severities, you can redirect them to a custom function for further processing, such as logging.
63+
64+
#### **Behavior:**
65+
- **`return true;`** → Completely suppresses errors of the excluded severities.
66+
- **`return false;`** → Uses PHP’s default error handler for the excluded severities.
67+
- **`return null|void;`** → Keeps using Blunder’s error handler as usual.
68+
69+
```php
70+
$run = new Run(new HtmlHandler());
71+
$run->severity()
72+
->excludeSeverityLevels([E_WARNING, E_USER_WARNING])
73+
->redirectTo(function ($errNo, $errStr, $errFile, $errLine) {
74+
error_log("Custom log: $errStr in $errFile on line $errLine");
75+
return true; // Suppresses output for excluded severities
76+
});
77+
```
78+
79+
**Example Use Case:**
80+
- Log warnings instead of displaying them.
81+
- Ensure deprecated notices are logged but not shown in production.
82+
83+
---
84+
85+
### 3. Redirect Excluded Severities to a New Handler
86+
You can also redirect excluded severities to a completely different error handler.
87+
88+
```php
89+
$run = new Run($errorHandler);
90+
$run->severity()
91+
->excludeSeverityLevels([E_WARNING, E_USER_WARNING])
92+
->redirectTo(function ($errNo, $errStr, $errFile, $errLine) {
93+
return new JsonHandler();
94+
});
95+
```
96+
**Effect:**
97+
- `E_WARNING` and `E_USER_WARNING` will be processed by `JsonHandler` instead of `HtmlHandler` or PHP’s default error handling.
98+
99+
---
100+
101+
**Note:**
102+
You can find a full list of available PHP error severities [here](https://www.php.net/manual/en/errorfunc.constants.php).
48103

49-
## Advanced Usage
104+
---
50105

51-
### Event Handling
106+
## Enabling or Disabling Trace Lines
107+
This allows you to control the level of detail shown in error messages based on your debugging needs.
108+
You can customize this behavior using the configuration:
109+
110+
```php
111+
$handler = new CliHandler();
112+
113+
// Enable or disable trace lines
114+
$handler->enableTraceLines(true); // Set false to disable
115+
116+
$run = new Run($handler);
117+
$run->load();
118+
```
119+
120+
### **Options:**
121+
- `true` → Enables trace lines (default in all cases except for in the CliHandler).
122+
- `false` → Disables trace lines, making error messages cleaner.
123+
124+
This allows you to control the level of detail shown in error messages based on your debugging needs.
125+
126+
## Remove location headers
127+
This will remove location headers and make sure that no PHP redirect above this code will execute.
128+
```php
129+
$run = new Run(new HtmlHandler());
130+
$run->removeLocationHeader(true);
131+
$run->load();
132+
```
133+
134+
## Setting the Exit Code for Errors
135+
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.
136+
```php
137+
$run = new Run(new CliHandler());
138+
$run->setExitCode(1);
139+
$run->load();
140+
```
141+
142+
## Event Handling
52143

53144
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.
54145

@@ -101,11 +192,34 @@ $run->event(function($item, $http) use($production) {
101192
$run->load();
102193
```
103194

104-
### HTTP Messaging
195+
## HTTP Messaging
105196

106197
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.
107198

108199
```php
109200
// $run = new Run(HandlerInterface, HttpMessagingInterface(ResponseInterface, ServerRequestInterface));
110201
$run = new Run(new HtmlHandler(), new HttpMessaging($response, $request));
202+
```
203+
204+
## Exception Chaining
205+
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.
206+
207+
To preserve the original exception’s file and line number while changing its type, you can use the **`preserveExceptionOrigin`** method provided by Blunder.
208+
209+
#### Example: Preserving the Original Exception’s Location
210+
```php
211+
try {
212+
// An exception has been triggered inside dispatch()
213+
$dispatch = $row->dispatch();
214+
} catch (Throwable $e) {
215+
// By default, rethrowing with a new exception class changes the error location
216+
$exception = new RuntimeException($e->getMessage(), (int) $e->getCode());
217+
218+
// Preserve the original exception's file and line number
219+
if (method_exists($e, "preserveExceptionOrigin")) {
220+
$e->preserveExceptionOrigin($exception);
221+
}
222+
223+
throw $exception;
224+
}
111225
```

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)