Slim Framework 自定义中间件中的错误处理


Error Handling in Slim Framework Custom Middleware

我正在尝试处理苗条框架自定义中间件中的错误,但不知道如何像在我的代码中那样做到这一点,如果请求不是四种特定类型,那么通过我想在 errorHandler 中处理的错误,具有适当的消息和状态,但目前此代码只是在 postman 中返回状态,响应正文中出现空白屏幕。我对SLIM不是很熟悉。提前致谢

<?php 
require 'vendor/autoload.php';
use 'Slim'App;
$c = new 'Slim'Container();
$c['notAllowedHandler'] = function ($c) { 
    return function ($request, $response, $methods) use ($c) {
        return $c['response']
            ->withStatus(405)
            ->withHeader('Allow', implode(', ', $methods))
            ->withHeader('Content-type', 'application/json')
        ->write(json_encode(array("c_status"=>"405","message"=>"Bad Request")));
    };
};
$c['notFoundHandler'] = function ($c) {
    return function ($request, $response) use ($c) {
        return $c['response']
            ->withStatus(404)
            ->withHeader('Content-type', 'application/json')
        ->write(json_encode(array("c_status"=>"404","message"=>"Not Found")));
    };
};

$c['errorHandler'] = function ($c) {
    return function ($request, $response, $exception) use ($c) {
        $data = [
            'c_status' => $response->getStatus(),
            'message' => $exception->getMessage()
        ];
        return $container->get('response')->withStatus($response->getStatus())
            ->withHeader('Content-Type', 'application/json')
            ->write(json_encode($data));
    };
};
$app = new App($c);
$app->add(function ($request, $response, $next) {
    if($request->isGet() || $request->isPost() || $request->isPut() || $request->isDelete()){
        $response = $next($request, $response);
    }else{
        $response = $response->withStatus(403);
    }
    return $response;
});
require 'API/routes.php';
$app->run();

抛出异常:

$app->add(function ($request, $response, $next) {
    if($request->isGet() || $request->isPost() || $request->isPut() || $request->isDelete()){
        $response = $next($request, $response);
    }else{
        throw new 'Exception("Forbidden", 403);
    }
    return $response;
})