/** * Finds the User model based on its primary key value. * If the model is not found,…
- User
/** * Finds the User model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param int id): ?User {
- Assistant
The use of
?Useras the return type means that the method can return either an instance ofUserornull.Looking at your docblock:
* @return User the loaded model * @throws NotFoundHttpException if the model cannot be foundYour method is documented to throw an exception if the model is not found, rather than returning
null.Therefore:
- If the method never returns
null(because it throws an exception when not found), the return type should be justUser, not?User. - If the method can return
null(no exception thrown), then?User(nullable User) is appropriate.
Conclusion
If your method throws
NotFoundHttpExceptionwhen the model is not found:protected function findModel($id): User - If the method never returns
- User
ErrorAction displays application errors using a specified view.
To use ErrorAction, you need to do the following steps:
First, declare an action of ErrorAction type in the actions() method of your SiteController class (or whatever controller you prefer), like the following:
public function actions() { return [ 'error' => ['class' => 'yii\web\ErrorAction'], ]; }
Then, create a view file for this action. If the route of your error action is site/error, then the view file should be views/site/error.php. In this view file, the following variables are available:
$name: the error name $message: the error message $exception: the exception being handledFinally, configure the "errorHandler" application component as follows,
'errorHandler' => [ 'errorAction' => 'site/error', ]
I need a basic but fully functional error.php file for the backend of a restful api admin mvc, that admin and helpers use to check and manage the data for the front end app.
- Assistant
Certainly! Since your backend is a RESTful API admin panel (MVC), the error view should be minimal but informative enough for admins and helpers to understand and debug the issue.
Here is a basic but fully functional
error.phpview forviews/site/error.php:<?php /* @var $this yii\web\View */ /* @var $name string */ /* @var $message string */ /* @var $exception Exception|null */ use yii\helpers\Html; $this->title = $name; ?> <div class="site-error"> <h1><?= Html::encode($this->title) ?></h1> <div class="alert alert-danger"> <?= nl2br(Html::encode($message)) ?> </div> <?php if (YII_DEBUG && $exception): ?> <h3>Exception Details:</h3> <pre><?= Html::encode($exception->__toString()) ?></pre> <?php elseif (!YII_DEBUG): ?> <p> An internal server error occurred. Please contact the administrator or try again later. </p> <?php endif; ?> </div>