composer require tinywan/exception-handler
config/exception.php
return [
// 这里配置异常处理类
'' => Tinywan ExceptionHandler Handler::class,
];
In multi-application mode, you can configure exception handling classes separately for each application, see Multi-application
Request parameter error
use support Request ;
use support Response ;
use Tinywan ExceptionHandler Exception BadRequestHttpException ;
class Token{
public function issueToken ( Request $ request ): Response
{
$ params = $ request -> post ();
if ( empty ( $ params )) {
throw new BadRequestHttpException ( '账号或密码不能为空' );
}
}
}
The above exception throws an error message in the following format:
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=utf-8
{
"code" : 0 ,
"msg" : "账号或密码不能为空" ,
"data" : {},
}
All returned exception information will be returned in json format. The above is
返回简略的异常信息
All exception error handlers adjust error display according to the debug
value in the configuration file config/app.php
When debug
value is true
(indicating that it is in debug mode), the error handler will display the exception and the detailed function call stack and source code. Line number to aid debugging, detailed exception information will be returned. When debug
value is false
, only error information will be displayed to prevent the leakage of sensitive information of the application, and brief exception information will be returned.
Return detailed exception information
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=utf-8
{
"code" : 0 ,
"msg" : " password不允许为空" ,
"data" : {
"request_url" : " POST //127.0.0.1:8888/oauth/issue-token " ,
"timestamp" : " 2022-03-06 15:19:12 " ,
"client_ip" : " 172.18.0.1 " ,
"request_param" : {
"username" : " webman "
},
"error_message" : " password不允许为空" ,
"error_trace": "#0 /var/www/webman-admin/app/functions.php(68): Tinywan\Validate\Validate->check(Array)n#1 /var/www/webman-admin/app/controller/Authentication.php(25): validate(Array, 'app\\common\\vali...')n#2 /var/www/webman-admin/vendor/workerman/webman-framework/src/App.php(234): app\controller\Authentication->issueToken(Object(support\Request))n#3 /var/www/webman-admin/app/middleware/AccessControlMiddleware.php(26): Webman\App::Webman\{closure}(Object(support\Request))n#4 /var/www/webman-admin/vendor/workerman/webman-framework/src/App.php(228): app\middleware\AccessControlMiddleware->process(Object(support\Request), Object(Closure))n#5 /var/www/webman-admin/vendor/workerman/webman-framework/src/App.php(137): Webman\App::Webman\{closure}(Object(support\Request))n#6 /var/www/webman-admin/vendor/workerman/workerman/Connection/TcpConnection.php(638): Webman\App->onMessage(Object(Workerman\Connection\TcpConnection), Object(support\Request))n#7 /var/www/webman-admin/vendor/workerman/workerman/Events/Select.php(295): Workerman\Connection\TcpConnection->baseRead(Resource id #254)n#8 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(2417): Workerman\Events\Select->loop()n#9 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(1541): Workerman\Worker->run()n#10 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(1383): Workerman\Worker::forkOneWorkerForLinux(Object(Workerman\Worker))n#11 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(1357): Workerman\Worker::forkWorkersForLinux()n#12 /var/www/webman-admin/vendor/workerman/workerman/Worker.php(549): Workerman\Worker::forkWorkers()n#13 /var/www/webman-admin/start.php(87): Workerman\Worker::runAll()n#14 {main}"
}
}
Add exception extended response data
throw new BadRequestHttpException ( '验证码错误' ,[
' data ' => [
' data1 ' => '自定义响应数据1 ' ,
' data2 ' => '自定义响应数据2 ' ,
]
]);
Custom extended response parameters will be added to the response
data
Add data
to return detailed exception information
{
"code" : 0 ,
"msg" : "验证码错误" ,
"data" : {
"request_url" : " POST //127.0.0.1:8888/oauth/issue-token " ,
...
"data1" : "自定义响应数据1 " ,
"data2" : "自定义响应数据2 "
}
}
Suppose you customize one: 405 Method Not Allowed
(meaning: the request method specified in the request line cannot be used to request the corresponding resource)
Custom exception classes only need to inherit TinywanExceptionHandlerExceptionBaseException
class
<?php
declare (strict_types= 1 );
namespace support exception ;
use Tinywan ExceptionHandler Exception BaseException ;
class MethodNotAllowedException extends BaseException
{
/**
* @var int
*/
public int $ statusCode = 405 ;
/**
* @var string
*/
public string $ errorMessage = '请求行中指定的请求方法不能被用于请求相应的资源' ;
}
use support Request ;
use support Response ;
use support exception MethodNotAllowedException ;
class Token{
public function issueToken ( Request $ request ): Response
{
$ params = $ request -> post ();
if ( empty ( $ params )) {
throw new MethodNotAllowedException ();
}
}
}
Use postman to request screenshots
JwtTokenException
ValidateException
More: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status
Usage scenarios
HTTP状态码
returned by the front-end is not 429
, but 200
or otherbody
is not {"code":0,"msg":"Too Many Requests"}
, but {"error_code":200,"message":"Too Many Requests"}
and other content Edit the status
HTTP status code of the config/plugin/tinywan/exception-handler/app.php
file
body
return content Edit the body
fields of the config/plugin/tinywan/exception-handler/app.php
file
The default option is
{
"code" : 0 ,
"msg" : " Too Many Requests " ,
"data" : null
}
Custom options reference one
1. Assume that the status
HTTP status code is set to 200
2. Assume that the body
array is set to
' body ' => [
' error_code ' => 200 ,
' message ' => '请求太多请稍后重试'
]
The response content is
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
{
"error_code" : 200 ,
"message" : "请求太多请稍后重试"
}
Others can be customized according to your own business
When the project requires a lot of customization, it is likely to need to extend Handler. In this case, you can inherit TinywanExceptionHandlerHandler
and modify the corresponding method.
Usage scenarios
xml
, not json format, just need to override the buildResponse
methodsolveExtraException
triggerNotifyEvent
Custom exception ErrorHandler
namespace support ;
use Illuminate Validation ValidationException ;
use Tinywan ExceptionHandler Handler ;
use Webman Http Response ;
class ErrorHandler extends Handler
{
/**
* @inheritDoc
*/
protected function solveExtraException ( Throwable $ e ): void
{
// 当前项目下的异常扩展
if ( $ e instanceof ValidationException) {
$ this -> errorMessage = $ e -> validator -> errors ()-> first ();
$ this -> errorCode = 422 ;
return ;
}
parent :: solveExtraException ( $ e );
}
/**
* @inheritDoc
*/
protected function triggerNotifyEvent ( Throwable $ e ): void
{
// ... 这里省略触发其他错误推送渠道
parent :: triggerNotifyEvent ( $ e );
}
/**
* @inheritDoc
*/
protected function buildResponse (): Response
{
// 构造自己项目下的响应
return json ([
' code ' => $ this -> statusCode , // 使用 statusCode 作为 code 返回
' msg ' => $ this -> errorMessage ,
' data ' => $ this -> responseData ,
]);
}
}
vendor/bin/phpstan analyse src
vendor/bin/php-cs-fixer fix src