laravel 自定义 ApiException

自定义示例

  • 1.打开app/Exceptions目录

定义一个类例如ApiException 专门用于返回api错误

<?php
## 继承Exception类

namespace App\Exceptions;

use Exception;

class ApiException extends Exception
{
    /*
     * author yaoLiuYang
     * date:2021/4/16
     */
    public function __construct($message = "")
    {
        $this->message = $message;
        parent::__construct($message);
    }
}
  • 2.使用示例
        try {
            $params = $request->only('id');
            $club = Club::find($params['id']);
            if ($club == null) {
               #抛出异常
                throw new ApiException('社团不存在');
            }
            $club->club_images = $club->clubGallery()->take(3)->pluck('img_url');
            return $this->success($club);
        } catch (ApiException $exception) {
               #这里自动捕获异常 
            return $this->error($exception->getMessage());
        }
上一篇:Hint: Fallback method 'public java.lang.String queryUserByIdFallback(java.lang.Long)' must


下一篇:Lending Club贷款数据转换与融合