laravel 优雅处理异常
2018年9月1日1.创建异常类
|
1 |
php artisan make:exception InvalidRequestException |
2.编辑异常类
打开app\Exceptions\InvalidRequestException.php 编辑文件
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App\Exceptions; use Exception; use Illuminate\Http\Request; #引入请求 class InvalidRequestException extends Exception { /** * 构造方法 * InvalidRequestException constructor. * @param string $message * @param int $code */ public function __construct(string $message = "", int $code = 400) { parent::__construct($message, $code); #调用父类的方法 } /** * 返回异常数据的方法 * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View */ public function render(Request $request) { if ($request->expectsJson()) { #如果是json请求 return response()->json(['msg' => $this->message], $this->code); #返回json提示的错误信息 } return view('pages.error', ['msg' => $this->message]); #返回错误视图 } } |
3使用异常类
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
use App\Exceptions\InvalidRequestException; #自定义异常类引用 . . . public function send(Request $request) { $user = $request->user(); #获取请求用户的用户数据 if ($user->email_verified) { #判断用户是否激活 throw new InvalidRequestException('你已经验证过邮箱了'); #如果激活告诉用户已经激活 } $user->notify(new EmailVerificationNotification()); #调用邮箱通知方法 return view('pages.success', ['msg' => '邮件发送成功']); #返回发送成功消息 } . . . |
4.屏蔽异常类输入到错误日志里,因为数据太多太长
打开 app\Exceptions\Handler.php编辑文件
|
1 2 3 |
protected $dontReport = [ InvalidRequestException::class, ]; |