捕获语法错误和自定义错误报告

问题描述 投票:0回答:2

我正在使用slim framework 3。我是这个框架的新手。我正在努力捕获错误并返回自定义JSON错误和消息。

我用这段代码来捕获notFoundHandler错误:

$container['notFoundHandler'] = function ($c) { 
    return function ($request, $response) use ($c) { 
        return $c['response'] 
            ->withStatus(404) 
            ->withHeader('Content-Type', 'application/json') 
            ->write('Page not found'); 
    }; 
};

但我能够捕获正常的语法错误。它显示警告:fwrite()期望参数2是字符串,在第42行的X-api \ controllers \ Products.php中给出的数组

我想要自定义错误来处理语法错误报告,而不是这条消息。我也用过这个,

$container['phpErrorHandler'] = function ($c) { 
    return function ($request, $response, $exception) use ($c) { 
        //Format of exception to return 
        $data = [ 
            'message' => "hello" 
        ]; 
        return $container->get('response')->withStatus($response->getStatus()) 
            ->withHeader('Content-Type', 'application/json') 
            ->write(json_encode($data)); 
    }; 
};

但不适合我。

slim
2个回答
0
投票

默认错误处理程序还可以包括详细的错误诊断信息。要启用此功能,您需要将displayErrorDetails设置为true:

$configuration = [
    'settings' => [
        'displayErrorDetails' => true,
    ],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);

请注意,这不适用于生产应用程序,因为它可能会显示您不希望透露的一些详细信息。你可以在Slim docs找到更多。

编辑

如果你需要处理parseErrors,那么你需要在容器中定义phpErrorHandler,就像你定义notFoundHandler一样。

$container['phpErrorHandler'] = function ($container) {
    return function ($request, $response, $error) use ($container) {
        return $container['response']
            ->withStatus(500)
            ->withHeader('Content-Type', 'text/html')
            ->write('Something went wrong!');
    };
};

注意:这仅适用于PHP7 +,因为在旧版本中无法捕获parseErrors。


0
投票

我在我的dependencies.php中使用了这个简短的代码

$container['errorHandler'] = function ($c) {
  return function ($request, $response) use ($c) {  
            $data = [
            'message' => "Syntex error"
            ];          
        return $c['response']
            ->withStatus(200)
            ->withHeader('Content-Type', 'application/json')
            ->write(json_encode($data));
    };
};



set_error_handler(function ($severity, $message, $file, $line) {
    if (!(error_reporting() & $severity)) {
        // This error code is not included in error_reporting, so ignore it
        return;
    }
    throw new \ErrorException($message, 0, $severity, $file, $line);
});

现在它为我工作。

© www.soinside.com 2019 - 2024. All rights reserved.