# 錯誤處理中間件
Things go wrong. You can’t predict errors, but you can anticipate them. Each Slim Framework application has an error handler that receives all uncaught PHP exceptions. This error handler also receives the current HTTP request and response objects, too. The error handler must prepare and return an appropriate Response object to be returned to the HTTP client.
> 事情出錯。
>
> 你不能預測錯誤,但你可以預測它們。
>
> 每個Slim 框架應用程序都有一個接收所有未捕獲的PHP異常的錯誤處理程序。
>
> 這個錯誤處理程序也接收當前的HTTP請求和響應對象。
>
> 錯誤處理程序必須準備并返回要返回給HTTP客戶機的適當響應對象。
## Usage
~~~php
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
/*
* 應該比ErrorMiddleware更早地添加路由中間件
* 否則,從中拋出的異常將不會由中間件處理
* The routing middleware should be added earlier than the ErrorMiddleware
* Otherwise exceptions thrown from it will not be handled by the middleware
*/
$app->addRoutingMiddleware();
/*
* @param bool $displayErrorDetails -> Should be set to false in production 在生產中應該設置為false
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler 參數傳遞給默認的ErrorHandler
* @param bool $logErrorDetails -> Display error details in error log 在錯誤日志中顯示錯誤細節
* which can be replaced by a callable of your choice.
* 它可以由您選擇的可調用項來替換。
* Note: This middleware should be added last. It will not handle any exceptions/errors
* 注意:這個中間件應該最后添加。它不會處理任何異常/錯誤
* for middleware added after it.
* 用于在它之后添加的中間件。
*/
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// ...
$app->run();
~~~
## 添加自定義錯誤處理程序
> 您現在可以為任何類型的異常或Throwable映射自定義處理程序。
You can now map custom handlers for any type of Exception or Throwable.
~~~php
<?php
use Psr\Http\Message\ServerRequestInterface;
use Slim\Factory\AppFactory;
use Slim\Psr7\Response;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Routing Middleware添加路由中間件
$app->addRoutingMiddleware();
// Define Custom Error Handler定義自定義錯誤處理程序
$customErrorHandler = function (
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
) use ($app) {
$payload = ['error' => $exception->getMessage()];
$response = $app->getResponseFactory()->createResponse();
$response->getBody()->write(
json_encode($payload, JSON_UNESCAPED_UNICODE)
);
return $response;
};
// Add Error Middleware添加錯誤中間件
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
// ...
$app->run();
~~~
## Error Logging錯誤日志
If you would like to pipe in custom error logging to the default`ErrorHandler`that ships with Slim you can simply extend it and stub the`logError()`method.
> 如果您希望將自定義錯誤日志傳輸到Slim附帶的默認`errorhandler`,您可以簡單地擴展它并存根` logerror()`方法。
~~~php
<?php
namespace MyApp\Handlers;
use Slim\Handlers\ErrorHandler;
class MyErrorHandler extends ErrorHandler
{
protected function logError(string $error): void
{
// Insert custom error logging function.插入自定義錯誤日志記錄功能。
}
}
~~~
~~~php
<?php
use MyApp\Handlers\MyErrorHandler;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Routing Middleware添加路由中間件
$app->addRoutingMiddleware();
// Instantiate Your Custom Error Handler實例化自定義錯誤處理程序
$myErrorHandler = new MyErrorHandler($app->getCallableResolver(), $app->getResponseFactory());
// Add Error Middleware添加錯誤中間件
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($myErrorHandler);
// ...
$app->run();
~~~
## Error Handling/Rendering
## 錯誤處理/渲染
The rendering is finally decoupled from the handling. It will still detect the content-type and render things appropriately with the help of`ErrorRenderers`. The core`ErrorHandler`extends the`AbstractErrorHandler`class which has been completely refactored. By default it will call the appropriate`ErrorRenderer`for the supported content types. The core`ErrorHandler`defines renderers for the following content types:
> 渲染最終從處理中解耦出來。
> 它仍然會檢測內容類型,并在`ErrorRenderers`的幫助下適當地呈現內容。
> 核心的`ErrorHandler`擴展了已經完全重構的`AbstractErrorHandler`類。
> 默認情況下,它會為支持的內容類型調用適當的`ErrorRenderer `。
> 核心`ErrorHandler`定義了以下內容類型的渲染器:
* `application/json`
* `application/xml`and`text/xml`
* `text/html`
* `text/plain`
For any content type you can register your own error renderer. So first define a new error renderer that implements`\Slim\Interfaces\ErrorRendererInterface`.
> 對于任何內容類型,您都可以注冊自己的錯誤渲染程序。因此,首先定義一個新的錯誤渲染,它實現了`\Slim\Interfaces\ErrorRendererInterface`。
~~~php
<?php
use Slim\Interfaces\ErrorRendererInterface;
class MyCustomErrorRenderer implements ErrorRendererInterface
{
public function __invoke(Throwable $exception, bool $displayErrorDetails): string
{
return 'My awesome format';
}
}
~~~
And then register that error renderer in the core error handler. In the example below we will register the renderer to be used for`text/html`content types.
> 然后將錯誤渲染注冊到核心錯誤處理程序中。在下面的例子中,我們將注冊用于`text/html`內容類型的渲染 。
~~~php
<?php
use MyApp\Handlers\MyErrorHandler;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
//
// Add Routing Middleware添加路由中間件
$app->addRoutingMiddleware();
//
// Add Error Middleware添加錯誤中間件
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
//獲取默認的錯誤處理程序并注冊我的自定義錯誤渲染 。
// Get the default error handler and register my custom error renderer.
$errorHandler = $errorMiddleware->getDefaultErrorHandler();
$errorHandler->registerErrorRenderer('text/html', MyCustomErrorRenderer::class);
// ...
$app->run();
~~~
### Force a specific content type for error rendering 為錯誤呈現強制指定內容類型
By default, the error handler tries to detect the error renderer using the`Accept`header of the request. If you need to force the error handler to use a specific error renderer you can write the following.
默認情況下,錯誤處理程序嘗試使用請求的`Accept`報頭檢測錯誤渲染程序。如果需要強制錯誤處理程序使用特定的錯誤渲染程序,可以編寫以下代碼。
~~~php
$errorHandler->forceContentType('application/json');
~~~
## New HTTP Exceptions 新的HTTP異常
We have added named HTTP exceptions within the application. These exceptions work nicely with the native renderers. They can each have a`description`and`title`attribute as well to provide a bit more insight when the native HTML renderer is invoked.
> 我們已經在應用程序中添加了命名的HTTP異常。這些異常與本地渲染程序配合得很好。它們都可以有一個`description`和`title`屬性,以便在調用本地HTML渲染程序時提供更多的信息。
The base class`HttpSpecializedException`extends`Exception`and comes with the following sub classes:
> 基類`HttpSpecializedException`擴展了`Exception`,并附帶了以下子類:
* HttpBadRequestException
* HttpForbiddenException
* HttpInternalServerErrorException
* HttpNotAllowedException
* HttpNotFoundException
* HttpNotImplementedException
* HttpUnauthorizedException
You can extend the`HttpSpecializedException`class if they need any other response codes that we decide not to provide with the base repository. Example if you wanted a 504 gateway timeout exception that behaves like the native ones you would do the following:
> 如果他們需要我們決定不提供的其他響應代碼,您可以擴展`httpspecializedexception`類。舉個例子,如果你想要一個504網關超時異常,它的行為和本地的一樣,你可以做以下事情:
~~~php
class HttpForbiddenException extends HttpException
{
protected $code = 504;
protected $message = 'Gateway Timeout.';
protected $title = '504 Gateway Timeout';
protected $description = 'Timed out before receiving response from the upstream server.';
}
~~~
- 開始
- 安裝
- 升級指南
- Web服務器
- 概念
- 生命周期
- PSR 7
- 中間件
- 依賴容器
- 實例 及通知和警告處理
- Request
- 請求方法
- 請求頭信息
- 請求主體
- 上傳的文件
- 請求幫助
- 路由對象
- Response
- 響應狀態
- 響應標頭
- 響應體
- 返回JSON
- 視圖模板
- 路由
- 創建路由
- 路由回調
- 路由策略
- 路線占位符
- 路由名
- 路由組
- 路由中間件
- 路由表達式緩存
- 容器識別解析
- 封裝中間件
- 路由的中間件
- 錯誤處理中間件
- 方法重寫的中間件
- 輸出緩沖中間件
- 內容長度中間件
- 擴展功能
- 以 / 結尾的路由模式
- 獲取當前路由
- 設置CORS
- 使用POST表單上傳文件
- 第三方組件
- slim-session
- auth
- slim-api-skeleton
- dir