Page 1 of 1

Using Exceptions for Form Errors/Messages

Posted: Tue Sep 25, 2007 12:33 am
by anjanesh
Hi

Im thinking of using a specific exception class for form errors generated by users - like mandatory input field left empty etc.

Code: Select all

class Ex_User extends Exception
 {
        public function __construct($message)
         {
                parent::__construct($msg);
         }
 }

try
 {
        //
 }
catch (Ex_MySQL $e)
 {
        //
 }
catch (Ex_User $e)
 {
        $msg = $e->getMessage(); // Display this msg in the html page as an error message to the user
 }
catch (Exception $e)
 {
        //
 }
But I remembered that Exception stores filename and linenumber and has stack tracing routines etc, exceptions are mainly designed for development errors, not for html-form messages.

Is it a bad idea to use an Exception for this purpose ?

Thanks

Posted: Tue Sep 25, 2007 3:33 am
by Jenk
You can use exceptions for any form of error handling, it is down to you (the developer) if the end user should see the full stack trace or not..

Code: Select all

catch (Exception $e) {
    echo "There has been an exception!"; // stack trace is not displayed..
}

Posted: Tue Sep 25, 2007 3:44 am
by Chris Corbyn
Although it's feasible to pop the error message into an exception it may be a little to abrupt. What if the user filled in more than one field incorrectly for example? Another way people deal with this is to setError($field, $message) in the $request object (or somewhere else that makes sense). Then you can just check if $request->hasErrors(), display them.

Posted: Fri Sep 28, 2007 12:46 am
by EricS
I'm more of the philosophy that "Exceptions should be EXCEPTIONAL!" Does that make sense?

I use exceptions a fair amount but those exception rarely if ever get thrown. And when they do, there is something very wrong going on like a database server is down or the OS is acting up. Things that I could really care less about the performance hit I'm taking for throwning the exception.

I ONLY use them to catch programming problems, not user error problems. They do come with quite a bit of overhead. And if your using them to catch user mistakes and forget to catch one, your user is left looking at a really ugly mess they should never have been exposed to.

Also as pointed out, you can paint yourself into a corner with exceptions if you need to keep track of multiple errors the user might have caused.

Posted: Fri Sep 28, 2007 9:54 pm
by Ambush Commander
What's nice about exceptions, however, is how they rewind the execution stack, when you otherwise would have needed to bubble up the error with special return values, etc. User errors, however, often change the execution flow of the program, so you need tight integration between the model and controller in these cases.