2016-03-31 10 views
0

私は次のコードでレスポンスに出力されることからエラーを防止するために、フレームワークのエラーハンドラに建てを再定義する方法についてのTシャツにスリムv3のドキュメント続く:Slim v3のエラーハンドラをどのように再定義できますか?

$settings = require __DIR__ . '/../src/settings.php'; 
$app = new \Slim\App($settings); 

// Errors to log rather than to end user 
$c = $app->getContainer(); 

$c['errorHandler'] = function ($c) { 
    return function ($request, $response, $exception) use ($c) { 
     $c['logger']->error("Error 500 diverted: ".$exception->getMessage()); 
     return $c['response']->withStatus(500) 
          ->withHeader('Content-Type', 'text/html') 
          ->write('Something went wrong on our side!'); 
    }; 
}; 

をそして、まだ私のAPIはまだありますSlimのデフォルトのハンドラを完全なスタックトレースで吐き出して、Slim Application Errorという文字列を吐き出すと便利ですが、私はこの情報をSlimのログ(モノログ)に送り、クライアントに面していることはあまりありません。このサービスの再定義が効果的に無視される理由はありますか?

+0

PHP7を使用していますか?だから、おそらくphpErrorHandlerが呼び出されますか? – danopz

+0

私は、実際には!それを見てみましょう。 – phrz

+0

https://akrabat.com/logging-errors-in-slim-3/こちらをご覧ください。 – geggleto

答えて

3

このコードは動作します:あなたが見ることができるように

<?php 
$app = new \Slim\App(); 
$container = $app->getContainer(); 

$container['errorHandler'] = function ($c) { 
    return function ($request, $response, $exception) use ($c) { 
     // log error here 
     return $c['response']->withStatus(500) 
          ->withHeader('Content-Type', 'text/html') 
          ->write('Something went wrong on our side!'); 
    }; 
}; 
$container['phpErrorHandler'] = function ($c) { 
    return function ($request, $response, $error) use ($c) { 
     // log error here 
     return $c['response']->withStatus(500) 
          ->withHeader('Content-Type', 'text/html') 
          ->write('Something went wrong on our side (again)!'); 
    }; 
}; 

$app->get('/exception', function ($req, $res, $args) { 
    // errorHandler will trap this Exception 
    throw new Exception("An error happened here"); 
}); 

$app->get('/php7', function ($req, $res, $args) { 
    $x = function (int $x) { 
     return $x; 
    }; 

    // phpErrorHandler wil trap this Error 
    $x('test'); 
}); 

$app->get('/warning', function ($req, $res, $args) { 
    $x = UNDEFINED_CONSTANT; 
}); 

$app->run(); 

、あなたはPHP 7 Errorsをキャッチする例外とphpErrorHandlerをキャッチするerrorHandlerを登録する必要があります。

いずれも、ルートで示されているようにPHP通知を受け取りません。それを理解するには、独自のエラーハンドラを登録する必要があります。

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

Slim v3のドキュメントでこれを逃したと私は気が気になりません! (もちろんそれがない限り) – phrz

関連する問題