[OK]をクリックすると、より見栄えの良い方法が見つかりました。 誰もがこれに続くlaravelに彼の例外ハンドラを改善したい場合:
アプリ/プロバイダが新しいサービス・プロバイダを作成する下では、プロジェクトのどこかにExceptionFactory
を作成
class ExceptionServiceProvider extends ServiceProvider {
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton(ExceptionFactory::class);
}
public function boot(ExceptionFactory $factory){
$factory->addException(UnauthorizedException::class, JsonResponse::HTTP_NOT_ACCEPTABLE);
$factory->addException(ConditionException::class, JsonResponse::HTTP_NOT_ACCEPTABLE, "Some Fixed Error Message");
}
}
ExceptionServiceProvider.php
それを呼び出すことができますコード&メッセージ
class ExceptionFactory{
private $exceptionsMap = [];
private $selectedException;
public function addException($exception, $code, $customMessage = null) {
$this->exceptionsMap[$exception] = [$code, $customMessage];
}
public function getException($exception){
if(isset($this->exceptionsMap[$exception])){
return $this->exceptionsMap[$exception];
}
return null;
}
public function setException($exception){
$this->selectedException = $exception;
}
public function getCode(){
return $this->selectedException[0];
}
public function getCustomMessage(){
return $this->selectedException[1];
}
}
ため
addException()
方法及びゲッターを含むクラス
次に左が行うすべてのレンダリング機能にExceptions/handler.php
内にある:覚えておくべき
private $exceptionFactory;
public function __construct(LoggerInterface $log, ExceptionFactory $exceptionFactory){
parent::__construct($log);
$this->exceptionFactory = $exceptionFactory;
}
public function render($request, Exception $e){
$error = new \stdClass();
$customException = $this->exceptionFactory->getException(get_class($e));
if(isset($customException)){
$this->exceptionFactory->setException($customException);
$error->code = $this->exceptionFactory->getCode();
$error->message = $e->getMessage();
$customMessage = $this->exceptionFactory->getCustomMessage();
if(isset($customMessage)){
$error->message = $customMessage;
}
}
return new JsonResponse($error, $error->code);
}
}
最後の事はちょうど追加config/app.php
の下でのアプリケーションの設定でServiceProvider
を置くことです:
\App\Providers\ExceptionServiceProvider::class
私がしたのと同じように、これが役に立つと思います。
漠然とした意見や主に意見に基づいたもの(**ベストプラクティス**など)を削除しました。 –