laravel异常处理
生活随笔
收集整理的這篇文章主要介紹了
laravel异常处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
laravel異常處理
1.場景:正常PC訪問時(shí),如點(diǎn)擊商品時(shí),此時(shí)商品剛好下架,那么要如何給出相應(yīng)的提示?
php artisan make:exception InvalidRequestException
從5.5版本后,支持在異常類中定義render()方法.異常觸發(fā)時(shí)會自動調(diào)用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() 方法第二個(gè)參數(shù)就是 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', '錯(cuò)誤')@section('content') <div class="card"><div class="card-header">錯(cuò)誤</div><div class="card-body text-center"><h1>{{ $msg }}</h1><a class="btn btn-primary" href="{{ route('root') }}">返回首頁</a></div> </div> @endsection3.當(dāng)出現(xiàn)異常時(shí),laravel默認(rèn)會寫到日志里,那么如何關(guān)掉因這個(gè)類而產(chǎn)生的日志呢
app/Exceptions/Handler.phpprotected $dontReport = [InvalidRequestException::class,];4.還有一種異常,即要給個(gè)信息到用戶看,也在存?zhèn)€信息到日志,而這倆錯(cuò)誤信息是不同的內(nèi)容時(shí):
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 = '系統(tǒng)內(nèi)部錯(cuò)誤', int $code = 500){parent::__construct($message, $code); //這里會自動存錯(cuò)誤到日志$this->msgForUser = $msgForUser;}public function render(Request $request){if ($request->expectsJson()) { //這里給上面指定的錯(cuò)誤信息給到用戶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 閱讀(...) 評論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/bing2017/p/10848904.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的laravel异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初识redis(redis基础命令)
- 下一篇: 及上一篇linux安装mysql的说明