laravel 如何用findOrFail捕捉类的父控件异常?

l2osamch  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(134)

在Laravel 9中,我创建了Repository类,在它的一个方法中,我调用了2个findOrFail

use Illuminate\Database\Eloquent\ModelNotFoundException;

class ArticleToManyVotesRepository
...

    public function store(int $id, int $manyItemId, array $data): JsonResponse|MessageBag
    {
        $article = Article::findOrFail($id);
        $vote = Vote::findOrFail($manyItemId);

        if ($article->votes()->where('vote_id', $manyItemId)->exists()) {
            throw new CustomManyToManyItemException('Article "' . $id . '" with vote ' . $manyItemId . ' already exists');
        }

        DB::beginTransaction();
        try {
            $article->votes()->attach($manyItemId, $data);
            DB::Commit();

        } catch (\Exception $e) {
            \Log::info(varDump($e->getMessage(), ' -1 STORE $e->getMessage()::'));
            DB::rollback();

            return sendErrorResponse($e->getMessage(), 500);
        }

        return response()->json(['result' => true], 201); // 201
    }

在父控制器中,我使用try块检查ModelNotFoundException:

public function articleManyVotesStore(Request $request, int $articleId, int $voteId)
{
    try {
        $data = $request->only('article_id', 'active', 'expired_at', 'supervisor_id', 'supervisor_notes');
        return $repository->store(id: $articleId, manyItemId: $voteId,
        data: $data);

    } catch (ModelNotFoundException $e) {
        return response()->json(['message' => $e->getMessage()], 404);
    }
    } catch (CustomManyToManyItemException $e) {
        return response()->json(['message' => $e->getMessage()], 500);
    }

}

但在存储方法中,有2个"findOrFail"调用,我可以通过哪种方式捕获findOrFail的有效异常?似乎findOrFail没有任何参数?
谢谢!

3htmauhk

3htmauhk1#

一种方法是比较异常模型名称空间,如下所示

try {
        $data = $request->only('article_id', 'active', 'expired_at', 'supervisor_id', 'supervisor_notes');
        return $repository->store(id: $articleId, manyItemId: $voteId,
            data: $data);

    } catch (ModelNotFoundException $e) {

        if($e->getModel() === Article::class){
            //add your logic here
        }elseif($e->getModel() === Vote::class){
            //add your logic here
        }
        return response()->json(['message' => $e->getMessage()], 404);
    }

相关问题