1.场景:正常PC访问时,如点击商品时,此时商品刚好下架,那么要如何给出相应的提示?
php artisan make:exception InvalidRequestException
从5.5版本后,支持在异常类中定义render()方法.异常触发时会自动调用render();
namespace AppExceptions; use Exception; use IlluminateHttpRequest; 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.php protected $dontReport = [ InvalidRequestException::class, ];
4.还有一种异常,即要给个信息到用户看,也在存个信息到日志,而这俩错误信息是不同的内容时:
php artisan make:exception InternalException
namespace AppExceptions; use Exception; use IlluminateHttpRequest; 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('商品未上架'); }