laravel新建异常类
1.新建异常类 php artisan make:exception ApiException
<?php namespace App\Exceptions; use Exception; use Throwable; class ApiException extends Exception { public function __construct($message = "", $code = 400, Throwable $previous = null) { parent::__construct($message, $code, $previous); } public function render() { return response()->json([ 'msg' => $this->message, 'code' => $this->code, ], $this->code); } }
2.方法中使用异常类
引入异常类 use App\Exceptions\ApiException; 方法中抛出异常 throw new ApiException('该商品不存在');
3.如果有使用Dingo,Dinggo会接管laravel的异常,render()方法不被执行,需要在服务提供者中屏蔽部分信息,找到app\Providers\AppServiceProvider.php中的boot方法,添加屏蔽代码
public function boot() { Schema::defaultStringLength(200); //有使用dinggo的话,添加如下代码屏蔽部分不需要显示内容 app('api.exception')->register(function (\Exception $exception) { $request = Request::capture(); return app('App\Exceptions\Handler')->render($request, $exception); }); }
4.新建的异常会被写进laravel的日志文件,不需要的可以在异常基类 app\Exceptions\Handler.php 中添加排除
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; class Handler extends ExceptionHandler { /** * 添加不需要写进laravel日志的异常类 * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ ApiException::class, ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. * * @return void */ public function register() { $this->reportable(function (Throwable $e) { // }); } }
可以手动写入
Log::error($this->message);
/********************************* 分割 **********************************/
新建异常类 php artisan make:exception ApiException
<?php namespace App\Exceptions; use Exception; use Illuminate\Support\Facades\DB; class ApiException extends Exception { public function __construct($message = "", $code = 0) { parent::__construct($message, $code); } public function render() { DB::rollBack(); return response()->json([ 'code' => $this->code, 'msg' => $this->message, ]); } }
try {
// 逻辑
} catch (ApiException $exception){
throw $exception;
} catch (\Exception $e){
Log::error('xxxxx : '.$e->getMessage().'---getFile :'.$e->getFile().'---getLine :'.$e->getLine());
throw new ApiException('活动参与人数较多,请重新尝试');
}