發現Slim總是把預設的Exception都搶走了,
導至完全無法使用try catch的功能,
只要使用預設的Exception,就會導到slim預設的error畫面
有幾種方式解決
1.重設slim的設定
$app = new \Slim\App;
$container = $app->getContainer();
$container['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
$data = [
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => explode("\n", $exception->getTraceAsString()),
];
return $c->get('response')->withStatus(500)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
這主要是將slim接到的exception訊息,轉成json。
2.自定Exception
首先建立一個新的class
class queryException extends Exception {
public function errorMessage() {
//error message
$errorMsg = $this->getMessage().' query err.';
return $errorMsg;
}
}
try {
throw new queryException('query Exception');
catch (queryException $e) {
/*
* 在此輸入要處理的程式碼
*/
}
沒有留言:
張貼留言