Reputation: 13
i was doing some refactoring of code on project in Yii2 framework.
I'm just asking if this can be written nicer, with less repetition (i try to follow DRY whenever i can). Any literature recommendation about this kind of topic is more than welcome, sorry for bad English.
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
if (isset($exception->statusCode)) {
if ($exception->statusCode == 500) {
return $this->render('error-500', ['exception' => $exception]);
} elseif ($exception->statusCode == 404) {
return $this->render('error-404', ['exception' => $exception]);
} else {
return $this->render('error', ['exception' => $exception]);
}
} elseif (isset($exception->code)) {
if ($exception->code == 500) {
return $this->render('error-500', ['exception' => $exception]);
} elseif ($exception->code == 404) {
return $this->render('error-404', ['exception' => $exception]);
} else {
return $this->render('error', ['exception' => $exception]);
}
}
} else {
$exception = new \yii\web\HttpException(500);
return $this->render('error-500', ['exception' => $exception]);
}
Upvotes: 1
Views: 147
Reputation: 1417
Another possible way
if ($exception !== null) {
$exceptionCode = isset($exception->statusCode)?$exception->statusCode:
( isset($exception->code)?$exception->code:null );
if($exceptionCode){
$viewFile = ($exceptionCode == 500)?'error-500':
( ($exceptionCode == 404)?'error-404':'error');
return $this->render($viewFile, ['exception' => $exception]);
} else {
// you need to something here
}
}
Upvotes: 1
Reputation: 133380
You can do so if you like
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
if (isset($exception->statusCode){
return $this-render('error-' . $exception->statusCode , ['exception' => $exception] );
} else if (isset($exception->code)) {
return $this-render('error-' . $exception->code , ['exception' => $exception] )
} else {
$exception = new \yii\web\HttpException(500);
return $this->render('error-500', ['exception' => $exception]);
}
}
or so if like more compact
if ($exception !== null) {
if (isset($exception->statusCode, $exception->code){
return $this-render('error-' . ($exception->statusCode) ? $exception->statusCode : $exception->code , ['exception' => $exception] );
} else {
$exception = new \yii\web\HttpException(500);
return $this->render('error-500', ['exception' => $exception]);
}
}
Upvotes: 2