Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in the model, or in the controller?

I asked around on various IRC channels but was unable to get an answer with a definitive explanation behind it. Should errors (pertaining to the model, such as transaction failures) be handled in the model, or in the controller?

Thanks in advance for any help.

EDIT

Well, the confusing thing is that my code (in the model) looks something like this already:

try
{
    // Connect to MongoDB
    // Fetch a record
}
catch (MongoConnectionException $e)
{
    // Handle this error
}
catch (MongoException $e)
{
    // Handle this error
}

So, should I return exceptions based on the exceptions MongoDB returns? Or should I directly allow these exceptions to bubble up to the controller?

Thanks!

like image 230
Jonathan Chan Avatar asked Dec 06 '25 07:12

Jonathan Chan


1 Answers

The correct answer is "Both", but mostly in the Model.

The appropriate thing for your controller to do is simply catch some exception that the model throws, and handle outputting a nice "whups" message. Depending on how you're structuring your models, it might be appropriate for the controller to do some logging.

Anything other than catching the exception, maybe writing to a log (if your model infrastructure doesn't do it), and displaying a pretty error, does not belong in your controller.

like image 52
timdev Avatar answered Dec 07 '25 20:12

timdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!