marcoazn89/booboo

处理生产中错误的框架

v2.3.0 2019-01-21 15:27 UTC

This package is not auto-updated.

Last update: 2024-09-28 17:59:59 UTC


README

composer require marcoazn89/booboo:dev-master

特性

  • 动态错误模板,用于生产错误
  • 内容协商以显示正确的错误格式(HTML、JSON、XML等)
  • 符合PSR-3规范(设置自己的记录器)
  • 符合PSR-7规范(传递带有头和状态码的响应对象)

运行BooBoo

这是您在应用程序开始时想要做的事情。

require '../vendor/autoload.php';

use Exception\BooBoo;

// This is a simple set up
BooBoo::setUp();

setUp()方法接受4个参数

  1. $logger: BooBoo默认使用error_log。如果您想使用自己的记录器,可以传递一个符合PSR-2的记录器,例如Monolog

  2. $traceAlwaysOn: 关闭或打开堆栈跟踪。默认情况下是关闭的。您可以在抛出异常时始终打开或关闭,但任何其他常规异常或PHP错误都将使用在设置中定义的设置

  3. $lastAction: 这是一个回调,在遇到错误时将在退出应用程序之前运行

  4. $ignore: 这是一个包含您想要忽略的PHP错误常量的数组。

// A more complex set up
BooBoo::setUp(
	$logger,
	true,
	function() { $textMessageService->send('Hey something broke');},
	[E_NOTICE, E_DEPRECATED]
);

当发生错误时会发生什么?

require '../vendor/autoload.php';

use Exception\BooBoo;

BooBoo::setUp();

// This causes a fatal error
$random->error();

BooBoo! BooBoo!

BooBoo会关注Accept头部

客户端请求JSON

BooBoo!

客户端请求XML

BooBoo!

创建异常和模板

  1. 只需扩展\Exception\BooBoo并实现两个抽象方法
class DatabaseException extends \Exception\BooBoo
{
	// It's good practice to define constants so that your exception messages are consistant
	const NOT_FOUND = 'Data requested was not found';
	
	/**
	 * This will be what's shown in the logs
	 * Example: [21-Mar-2016 05:58:27 Europe/Berlin] <TAG>: Something bad happened
	 */
	protected function getTag()
	{
		return 'DbException';
	}
	
	/**
	 * Return an array that defines your error template location or strings.
	 * For any template that is not defined, BooBoo will use its default templates.
	 * There are 4 templates currently supported: html, text, xml, json
	 */
	protected function getTemplates()
	{
		return [
			'html' => "<p>Something went really <h1>WRONG!</h1></p>",
			'json' => __DIR__ . '/json.php'
		];
	}
}
  1. 模板将注入以下变量
  • $response: PSR-7响应对象
  • $message: 为模板定义的消息或null(如果没有提供)
  • $data: 传递给模板的任何数据或null(如果没有提供)
<?php
// Let's use json.php that was defined as a template in the previous example
{
    "status": <?php echo $response->getStatusCode();?>,
    "description": "<?php echo $response->getReasonPhrase(); ?>",
    "message": "<?php if (!empty($data)) echo $data; else echo 'Please try again later'; ?>",
    "data": <?php if (!empty($data)) echo json_encode($data); else echo null; ?>
}
  1. 抛出异常
// Lets use DatabaseException defined above for this example
// Note that the exceptions you define still work as a regular exception so you can just do a simple throw like:
throw new DatabaseException('Data was not found. The table appears to be empty');

// Or (showing all the options for documentation purposes)
throw (new DatabaseException('Data was not found. The table appears to be empty'))
	//Passing a response object with 400 status code.
	//Please not that BooBoo ignores any status code below 400 and turn it into 500
	->response($response->withStatus(400))
	
	//Use the constant defined for the message displayed to the client
	->displayMessage(DatabaseException::NOT_FOUND)
    	
	//Add context to your logs
	->logContext(['sessionID' => 12345])
    	
	//Pass data to your template
	->templateData(['actions' => 'Contact support'])
    	
	// Turn off stack traces
	->trace(false);
    	
	// Tur off logging
	->noLog();

限制您能支持的内容

添加支持顺序很重要!这将忽略任何不匹配支持类型的Accept头部。更多信息请参阅http-wrapper

require '../vendor/autoload.php';

use BooBoo\BooBoo;

// Add supported types
\HTTP\Support\TypeSupport::addSupport([
	\HTTP\Response\ContentType::HTML,
	\HTTP\Response\ContentType::TEXT
]);

BooBoo::setUp();

// Assume the client sends a text Accept header, the response will
// be in plain text because is the best match. If none match, the
// response will be in HTML because it was the first one added
$random->error();

BooBoo如何将错误与HTTP响应关联起来

  • 任何HTTP 500+状态码和致命错误将转换为关键日志级别,因为它们是系统错误。
  • 任何400范围内的HTTP状态码将转换为警告日志级别,因为它们是客户端生成的错误。这仅适用于您通过扩展BooBoo定义的异常。
  • 任何PHP非致命错误或消息将转换为错误日志级别。