doucheng7808 2018-06-19 03:33
浏览 64
已采纳

Laravel对404的所有例外

the question is simple. Using laravel 5.6

I have for example, this route

Route::get('/services/{id}/{service}', ['as'=> 'services.show', 'uses' => 'ServicesController@show']);

where inside controller I do some fancy logic.

the question is: is there any other elegant way to throw a 404 when something fails inside the controller rather than the typical ErrorException page from laravel? (this is not the 404).

An easy example could be the id is not inserted in the database, so that is making the app fails, not returning a 404.

I guess one solution should be insert a try catch condition and if it fails render(404).. more or less..

  • 写回答

3条回答 默认 最新

  • dpfw3607 2018-06-19 04:11
    关注

    Go to app/Exceptions If there is render method change it, or add the method.

    Ex:

    public function render($request, Exception $exception)
    {
        if($exception instanceof NotFoundHttpException){
            return response()->view('errors/404', ['invalid_url'=>true], 404);
        }
    
        if ($exception instanceof TokenMismatchException && Auth::guest()) {
            error_log('Error :' . $exception->getMessage());
            abort(500);
        }
    
        if ($exception instanceof TokenMismatchException && getenv('APP_ENV') != 'local') {
            return redirect()->back()->withInput();
        }
    
        if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException && getenv('APP_ENV') != 'local') {
            error_log('Error :' . $exception->getMessage());
            abort(404);
        }
    
        if(($exception instanceof PDOException || $exception instanceof QueryException) && getenv('APP_ENV') != 'local') {
            error_log('Error :' . $exception->getMessage());
            abort(500);
        }
    
        if ($exception instanceof ClientException) {
            error_log('Error :' . $exception->getMessage());
            abort(500);
        }
    
        return parent::render($request, $exception);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度