0
点赞
收藏
分享

微信扫一扫

laravel 自定义 ApiException 继承 Exception


阅读目录

  • Laravel异常处理API数据返回
  • 1.创建异常
  • 2.异常类
  • 3调用方式
  • laravel 自定义 ApiException 继承 Exception
  • try 捕获异常示例
  • throw 直接抛出异常示例
  • render 方法
  • Laravel 方法知识点
  • firstOrCreate
  • firstOrNew
  • updateOrCreate
  • 总结

Laravel异常处理API数据返回

1.创建异常

创建自定义异常类:php artisan make:exception CommonException 生成文件地址:laravel5\app\Exceptions

2.异常类

<?php

namespace App\Exceptions;

use Exception;

class CommonException extends Exception
{
    public $message =array(
        500002 => '最近一次同步时间格式不正确!',
        500003 => 'sql语句错误',
    );
    public function __construct($code)
    {
        parent::__construct($this->message[$code], $code);
    }

    /**
     * 报告异常
     *
     * @return void
     */
    public function report()
    {
        // dd(111);
    }

    /**
     * 转换异常为 HTTP 响应
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render()
    {
         return response()->json([
             'code' => $this->getCode(),
             'message' => $this->getMessage(),
        ]);
    }
}

3调用方式

try {
	# 第一个参数为条件,第二个参数为对应需要更新或创建的值
	Model::updateOrCreate(['id'=>100000,'valid'=>1],['va'=>100000,'cc'=>1]);
} catch (Exception $e) {
	throw new CommonException(500002);
}catch(\Illuminate\Database\QueryException $ex) {
	// laravel捕获sql错误码及错误信息 此处信息需继续添加
	throw new CommonException(500003);
}

预览效果:

laravel 自定义 ApiException 继承 Exception_Laravel

laravel 自定义 ApiException 继承 Exception_php_02

laravel 自定义 ApiException 继承 Exception

<?php
## 继承Exception类
namespace App\Exceptions;
use Exception;

class ApiException extends Exception
{
    public const SYSTEM_ERROR_CODE = 10000;
    public const SYSTEM_ERROR_CODE_MSG = '$club变量不存在';

    private static $error_config = [
        self::SYSTEM_ERROR_CODE => self::SYSTEM_ERROR_CODE_MSG,
    ];

    public function __construct($code = self::SYSTEM_ERROR_CODE, $message = self::SYSTEM_ERROR_CODE_MSG)
    {
        if (isset(static::$error_config[$code])) {
            $message = static::$error_config[$code];
        }
        parent::__construct($message, $code);
    }
}

try 捕获异常示例

try {
    throw new ApiException(1111,'自定义ApiException');
}catch (ApiException $exception) {
    return $exception->getMessage();
};

throw new ApiException(ApiException::SYSTEM_ERROR_CODE);

laravel 自定义 ApiException 继承 Exception_App_03


throw new ApiException(1111,'自定义ApiException');

laravel 自定义 ApiException 继承 Exception_php_04

throw 直接抛出异常示例

laravel 自定义 ApiException 继承 Exception_Laravel_05

render 方法

<?php
## 继承Exception类
namespace App\Exceptions;
use Exception;

class ApiException extends Exception
{
    public const SYSTEM_ERROR_CODE = 10000;
    public const SYSTEM_ERROR_CODE_MSG = '$club变量不存在';

    private static $error_config = [
        self::SYSTEM_ERROR_CODE => self::SYSTEM_ERROR_CODE_MSG,
    ];

    public function __construct($code = self::SYSTEM_ERROR_CODE, $message = self::SYSTEM_ERROR_CODE_MSG)
    {
        if (isset(static::$error_config[$code])) {
            $message = static::$error_config[$code];
        }
        parent::__construct($message, $code);
    }

    public function render()
    {
        return response()->json([
            'code' => $this->getCode(),
            'message' => $this->getMessage(),
        ]);
    }
}

控制器

<?php
namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use Illuminate\Http\Request;

class TxtController extends Controller
{
    public function createOrder(Request $request)
    {
        throw new ApiException(1111,'自定义ApiException');
    }

}

laravel 自定义 ApiException 继承 Exception_自定义_06

Laravel 方法知识点

Laravel 里 firstOrCreate、firstOrNew、updateOrCreate 方法使用。

firstOrCreate

firstOrCreate 方法将会使用指定的字段 => 值对,来尝试寻找数据库中的记录。

如果在数据库中找不到,5.5 以下版本会使用属性来添加一条记录,5.5 及以上版本则将使用第一个参数中的属性以及可选的第二个参数中的属性插入记录。

用法:

User::firstOrCreate(['name' => 'Lisi']);
User::firstOrCreate(['name' => 'Lisi'], ['age' => 20]);  // 5.5及以上版本支持

查看源码:

# 小于 5.5 版本,只有一个参数
public function firstOrCreate(array $attributes)
{
    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }
    $instance = $this->model->newInstance($attributes);
    $instance->save();
    return $instance;
}

# 5.5 版本
public function firstOrCreate(array $attributes, array $values = [])
{
    // 判断是否存在,如果存在,返回实例
    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }

    // 不存在创建,此代码简化就是 $this->newModelInstance($attributes + $values)->save();
    return tap($this->newModelInstance($attributes + $values), function ($instance) {
        $instance->save();
    });
}

firstOrNew

会尝试使用指定的属性在数据库中寻找符合的纪录。如果未被找到,将会返回一个新的模型实例。

请注意 firstOrnew 返回的模型还尚未保存到数据库。

你需要通过手动调用 save 方法来保存它

用法:

User::firstOrNew(['name' => 'Lisi']);
User::firstOrNew(['name' => 'Lisi'], ['age' => 20]); // 5.5及以上版本支持

查看源码:

# 小于 5.5 版本,只有一个参数
public function firstOrNew(array $attributes)
{
    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }
    return $this->model->newInstance($attributes);
}

# 5.5 版本
public function firstOrNew(array $attributes, array $values = [])
{
    if (! is_null($instance = $this->where($attributes)->first())) {
        return $instance;
    }
    return $this->newModelInstance($attributes + $values);
}

查看源码就更清楚 firstOrCreatefirstOrNew 多了save 方法,两个方法都很实用,根据场景使用它。

updateOrCreate

更新数据,如果不存在则创建,这个函数就充分利用到了方法 firstOrNew,此函数版本之间变化不大

用法:

User::updateOrCreate(['name' => 'Lisi'], ['age' => 20]);

查看源码:

# 5.5 版本
public function updateOrCreate(array $attributes, array $values = [])
{
    return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
        $instance->fill($values)->save();
    });
}

总结

firstOrCreate:判断之后直接入库

firstOrNew:判断之后还要做其他业务流程,之后再入库

updateOrCreate:更新数据,如果不存在则创建


举报

相关推荐

0 条评论