日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

laravel异常处理

發布時間:2025/5/22 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 laravel异常处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
laravel異常處理

1.場景:正常PC訪問時,如點擊商品時,此時商品剛好下架,那么要如何給出相應的提示?

php artisan make:exception InvalidRequestException

從5.5版本后,支持在異常類中定義render()方法.異常觸發時會自動調用render();

namespace App\Exceptions;use Exception; use Illuminate\Http\Request;class InvalidRequestException extends Exception {public function __construct(string $message = "", int $code = 400){parent::__construct($message, $code);}public function render(Request $request){if ($request->expectsJson()) {// json() 方法第二個參數就是 Http 返回碼return response()->json(['msg' => $this->message], $this->code);}return view('pages.error', ['msg' => $this->message]);} }

2.再在view/pages/error.blade.php里做好模板

@extends('layouts.app') @section('title', '錯誤')@section('content') <div class="card"><div class="card-header">錯誤</div><div class="card-body text-center"><h1>{{ $msg }}</h1><a class="btn btn-primary" href="{{ route('root') }}">返回首頁</a></div> </div> @endsection

3.當出現異常時,laravel默認會寫到日志里,那么如何關掉因這個類而產生的日志呢

app/Exceptions/Handler.phpprotected $dontReport = [InvalidRequestException::class,];

4.還有一種異常,即要給個信息到用戶看,也在存個信息到日志,而這倆錯誤信息是不同的內容時:

  php artisan make:exception InternalException

namespace App\Exceptions;use Exception; use Illuminate\Http\Request;class InternalException extends Exception {protected $msgForUser;public function __construct(string $message, string $msgForUser = '系統內部錯誤', int $code = 500){parent::__construct($message, $code); //這里會自動存錯誤到日志$this->msgForUser = $msgForUser;}public function render(Request $request){if ($request->expectsJson()) { //這里給上面指定的錯誤信息給到用戶return response()->json(['msg' => $this->msgForUser], $this->code);}return view('pages.error', ['msg' => $this->msgForUser]);} }

?在控制器中就直接這么用

if (!$product->on_sale) {throw new InvalidRequestException('商品未上架');}

?

posted on 2019-05-11 15:51 greatbing 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/bing2017/p/10848904.html

《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的laravel异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。