echo_'s avatar
Level 7

Try Catch database related operation (Create, Update, Delete)

Do you Thinks we should try catch all Create, Update and Delete operations in laravel ?

Ex :

try{
// Could be Category::update() ; $category->delete();
	Category::create(["name"=>"my_category"])
} catch(\Exception $e){
	Log::error($e->getMessage()
}

Or not ?

0 likes
5 replies
martinbean's avatar

@echo_ No. That’s what the exception handler is for. Otherwise you’re just gobbling up exceptions and losing any helpful information to diagnose the actual issue, such as the stack trace.

1 like
echo_'s avatar
Level 7

@martinbean thanks for you're reply. is it not possible to pass the stack through the all try catch ?

martinbean's avatar

is it not possible to pass the stack through the all try catch ?

@echo_ Why? Why catch the exception, if you’re just going to throw the exact same information again?

Snapey's avatar
Snapey
Best Answer
Level 122

Only use try-catch if there is something you might be able to do about the error. In your example, the user (and the rest if your code) will assume that all is well, and other errors might then occur which are then harder to diagnose. For instance, in your example you might redirect to a page with the resource just created, but it wasnt created and now you are looking at a 404 error with no obvious reason.

1 like

Please or to participate in this conversation.