2016-12-21 54 views
0

我正在使用苗條框架3。我是這個框架的新手。我正在努力捕獲錯誤並返回自定義JSON錯誤和消息。捕捉syntex錯誤和自定義錯誤報告

我用這個代碼來捕獲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'); 
    }; 
}; 

但我能趕上正常了Syntex錯誤。 是表示警告:fwrite()將期望參數2爲字符串,在X-API \控制器給定陣列\ Products.php第42行

代替此消息時,我希望我的定製的錯誤處理了Syntex錯誤報告。 我也用過這個,

$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)); 
    }; 
}; 

但是不適合我。

回答

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

我已經完成了這個配置。但是,而不是默認的錯誤處理程序,我希望我的自定義錯誤處理使用苗條框架。 – Vijay

+0

我已經更新了答案。 –

+0

我也已經在我的問題中定義了phpErrorHandler。請參閱我的問題 – Vijay

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); 
}); 

它爲我工作。