简体   繁体   中英

Method error handling for user friendly messages

I have an object oriented app (written in an MVC framework) and often my error handling procedures are ad-hoc. Sometimes I return 0 for no error, sometimes a true for success. In general there is not a lot of consistency.

My scenario is that I have a controller calling a method from my model. If that method fails, I want it to return a human-readable reason as to why the error could not be completed. This error will be passed on to the user. For instance a userDelete() method. I just want to know whether the user was deleted, and if not, why?

My previous approach was to return true if deleted, and a string otherwise. This made if statements a little tricky because

if ($output = $this->someMethod())

will return true for a string, so that doesn't help much.

My considerations for alternatives are:

Return an array

array ('status'=>'error', 'message' => 'You did not specify an existing user')

This will be compatible with the if statement shown above (ie will return 'false' when an array is returned). I would return true for a successful function call.

Use PHP's Exception class and try/catch blocks

When the code falls into an error (ie perform a check to see whether user exists, and it turns out negative)

if ($query->count == 0) {
   throw new Exception("User does not exist");
}

and then on the calling page I would write:

try {
   $this->someMethod();
} catch (Exception $e) {
   echo $e->getMessage() //Or some other way of handling the error
}

If I proceed with this alternative, is that "bad form" in PHP? Should Exceptions be only used for actual coding errors (ie division by 0) instead of for 'higher level' application error handling / user feedback?

Remember: I plan on sending these error messages back to the user at some point during execution ... should I be concerned that other Exceptions thrown by PHP itself will make their way back to the user? Should I extend the Exception class to prevent this?

Personally I use something similar to your array idea since I can return and store that status and all other pieces of useful log info if I need to. If all goes well I simply return an empty array for consistency since if(someFunct()) would be true on success (if I used true as success) or on non-empty array. This way I just equate empty array (!someFunc()) to be success.

However, feel free to look at this post which I found to be pretty good about this topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM