Answer the question
In order to leave comments, you need to log in
Catching exceptions in Laravel. What is the most correct way?
Hello members!
I took Laravel Boilerplate as a basis, I write in the image and likeness, but I have questions.
Now there is the following code for saving the record:
In the repository:
public function create(array $data) : Document
{
return DB::transaction(function () use ($data) {
$document = $this->model::create([
'number' => $data['number'],
// ....
]);
if ($document) {
return $document;
}
throw new GeneralException(__('exceptions.backend.common.create_error'));
});
}
public function store(Request $request)
{
$this->documentRepository->create($request->only(
'number',
// ....
));
return redirect()->route('admin.docflow.document.list')
->withFlashSuccess(__('alerts.backend.common.created'));
}
public function create(array $data) : Document
{
try {
return DB::transaction(function () use ($data) {
$document = $this->model::create([
'number' => $data['number'],
// ....
]);
if ($document) {
return $document;
}
throw new GeneralException(__('exceptions.backend.common.create_error'));
});
} catch (\Exception $e) {
throw new GeneralException($e->getMessage());
}
}
Answer the question
In order to leave comments, you need to log in
1. In what layer is it customary to handle such situations?Depends on the application logic, there is no clear answer.
2. What kind of catch to catch most of the exceptions? Should you use \Exception?\Throwable will catch everything. Whether this is a good idea is a debatable question, there is no single answer.
3. Should I do this:If there are real good reasons, then it's worth it. No no. There is no such reason in your question.
I thought the framework somehow out of the box knows how to handle such situations.Can .
Nobody should catch them. Not the framework, not you.
This is what should get into your log, from there notify you of the problem and you must fix it. What is the point of replacing QueryException with your GeneralException, and even without specifying $previous as the third argument of the exception'a constructor? What would lose the stack trace? Why do this at all?
This is an internal server error. It should not be caught anywhere, right up to the App\Exceptions\Handler handler.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question