如何在findOrFail类的父控制中捕获异常?



在Laravel 9中,我创建了Repository类,并在其中一个方法中使用了2 findOrFail调用

use IlluminateDatabaseEloquentModelNotFoundException;
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
}

在父控制器我有尝试块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);
}
}

但是在store方法中有2个调用"findOrFail"以何种方式我可以捕获findOrFail的有效异常?似乎findOrFail没有任何参数?

谢谢!

一种方法是像下面这样比较异常模型命名空间

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);
}