Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Handling in Model (MVC)

I was wondering what the excepted standard is for handling errors in the Model.

Currently I have 'setError' and 'getError' methods that's in use by all my Models.

This means I'm only concerned with whether a call to a method in my Model is true or false. If it's false then I would use $this->model->getError() in my Controller.

Additionally I'm contemplating setting up a separate file that contains all my errors. One file per model, also wanted to have thoughts on this.

like image 446
Andre Avatar asked Sep 20 '09 21:09

Andre


3 Answers

A simpler solution would be to use exceptions.

When an error occurs that would be something you display to a user, throw a special kind of an exception - perhaps named UserError. The exception should contain the text of the error message when you throw it. These kinds of errors are features which provide users with useful information (i.e. they attempted to delete something that did not exist - which can happen when they have multiple browsers open, etc.)

e.g.:

throw new UserError("That object no longer exists.");

When an error occurs that you want to hide from the user, throw a different kind of exception, perhaps named InternalError. You would want to log this and allow the program to continue, so the specific error is hidden from the user. If it prevents something from happening, you might want to throw up a generic error message. These would be bugs and you want to fix them as soon as possible.

e.g.:

throw new InternalError("Failed to connect to remote service");

All of the error messages can be stored (hard-coded) in the source where the exception is thrown. This is not necessarily a bad design practice - if you use a tool like gettext, you can easily translate all of these messages.

like image 109
Fragsworth Avatar answered Oct 04 '22 06:10

Fragsworth


I've been using log4j and log4cxx and logging to a syslogd. Kiwi is a simple Win32 syslogger that will track your log messages and save them to a file. Log4j / Log4cxx have configuration files that you can use to setup all your log levels or log message destinations (you can log to multiple places).

It takes so little effort to setup and use, and it works like a charm.

I haven't tried out log4php myself.

Exceptions are good when you no longer want your program to continue executing. Catch exceptions at a high level where you can accept the fall-out of failed executions.

like image 44
Kieveli Avatar answered Oct 04 '22 07:10

Kieveli


Review the NerdDinner tutorial on how to create validation routines before making a final decision:

http://nerddinnerbook.s3.amazonaws.com/Part3.htm

The Validation part is about 2/3 of the way down the page.

like image 36
Robert Harvey Avatar answered Oct 04 '22 06:10

Robert Harvey