防止显示 laravel 消息并将用户重定向到 Laravel 5 中的自定义页面问题



我想以某种方式捕获 laravel 错误,警告消息。我不想从配置/应用程序.php文件中禁用它们。 我正在使用 monolog 来记录一些信息。这是我的代码:

public function view($id){
   try {
     $tag = Tags::find(12313);   // tags is a model
   }catch(Exception $error){
        echo 'error'; exit();
        $this->log->logMessage(Logger::ERROR, $error->getMessage());
        return redirect()->route('admin.tags')->with(['msg' => 'Smth went wrong']);
   }
}

$this->log是一个类,我在其中使用monolog class来记录信息。

事实是,现在,它没有进入捕获部分。我没有收到error消息。我从拉拉维尔那里收到这条消息:

Trying to get property of non-object (View: ......

我故意把号码放在那里12313,看看它是否有效。并且由于某种原因不起作用,我没有被重定向.这个想法,如果发生了什么事,我想将用户重定向到带有一般错误消息的特定页面。我怎样才能做到这一点?

你可以在 laravel 中做到这一点。您可以在 App\Exceptions\Handler 类中处理错误

  public function render($request, Exception $exception)
    {
        if($exception instanceof NotFoundHttpException)
        {
           return response()->view('errors.404', [], 404);
        }
          if ($exception instanceof MethodNotAllowedHttpException) 
        {
                return response()->view('errors.405', [], 405);
        }
         if($exception instanceof MethodNotAllowedHttpException)
        {
           return response()->view('errors.404', [], 405);
        }
        return parent::render($request, $exception);
    }
如果未

找到记录,find()方法不会引发异常。所以这样做:

public function view($id)
{
    $tag = Tags::find(12313);   // tags is a model
    if (is_null($tag)) {
        $this->log->logMessage(Logger::ERROR, $error->getMessage());
        return redirect()->route('admin.tags')->with(['msg' => 'Smth went wrong']);
    }
}

或者使用 findOrFail()如果未找到指定的记录,它将引发异常。

有时,如果找不到模型,您可能希望引发异常。这在路由或控制器中特别有用。findOrFail和firstOrFail方法将检索查询的第一个结果;但是,如果未找到结果,则会抛出IlluminateDatabaseEloquentModelNotFoundException

最新更新