473,379 Members | 1,245 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Exception error handling?

348 100+
Hey all.. again. :)

I am wondering how to go about getting the errors from the database layer to echo to the UI?

If mysql throws an error, how can I echo that to the browser? Am I correct in going about it like this?

[php]
die($_POST['myerror'] = mysql_error());
echo $_POST['myerror'];
[/php]

Would it be like that or is there some other way of doing this?

Thanks.

Frank
Oct 18 '07 #1
5 2099
ronverdonk
4,258 Expert 4TB
You can display a MySQL error right after the MySQL command issued, e.g.
[php]
$conn = mysql_connect("localhost", "xxxx", "yyyy")
or die("Could not connect to the db server: ".mysql_error());

or

$result = mysql_query("myquery") or
die("Query resulted in an error: " . mysql_error());
[/php]
Ronald
Oct 18 '07 #2
pbmods
5,821 Expert 4TB
Heya, Frank.

In PHP 5, the preferred method for signaling a major malfunction is the Exception class.

Expand|Select|Wrap|Line Numbers
  1. function doQuery( $sql )
  2. {
  3.     global $db;
  4.  
  5.     $__res = mysql_query( $sql, $db );
  6.  
  7.     if( $_err = mysql_error($db) )
  8.     {
  9.         throw new Exception("[doQuery]\nQuery:\n{$sql}\n\nError:\n{$_err}");
  10.     }
  11.  
  12.     // Am I the only person in the universe that does this?
  13.     preg_match_all( '/\\b\\w+\\b/', $sql, $__matches );
  14.     switch( strtolower($__matches[0][0]) )
  15.     {
  16.         case 'select':
  17.             $_resultSet = array();
  18.             while( $__row = mysql_fetch_assoc($__res) )
  19.             {
  20.                 $_resultSet[] = $__row;
  21.             }
  22.         break;
  23.  
  24.         case 'insert':
  25.             $_resultSet = mysql_insert_id($db);
  26.         break;
  27.  
  28.         .
  29.         .
  30.         .
  31.     }
  32.  
  33.     if( is_resource($__res) )
  34.     {
  35.         mysql_free_result($__res);
  36.     }
  37.  
  38.     return $_resultSet;
  39. }
  40.  
Oct 18 '07 #3
fjm
348 100+
Thanks guys! Now I am started down the right track on exception handling.

What would be the difference if I used php's exception handling try / catch over say, Ronald's (Ronverdonk) suggestion?

What I was wanting to do was to have a general error message screen and update that screen with a session variable. The only way I can see to do that would be to use Ronverdonk's suggestion and save the error into a session then echo that to the browser. Am I wrong?

Is this possible with the catch / try method?


Thanks for the input!

Frank
Oct 19 '07 #4
pbmods
5,821 Expert 4TB
Heya, Frank.

The main advantage to using try/catch is that you can catch Exceptions *anywhere*.

For example (and using the doQuery() function above):
Expand|Select|Wrap|Line Numbers
  1. function runABadQuery()
  2. {
  3.     doQuery( 'this is not valid SQL' );
  4. }
  5.  
  6. ob_start();
  7.  
  8. try
  9. {
  10.     echo 'You will never see this.';
  11.  
  12.     runABadQuery();
  13.  
  14.     echo 'You will never see this, either.';
  15. }
  16. catch( Exception $e )
  17. {
  18.     // Alert admin
  19.     mail
  20.     (
  21.         'my@email.address',
  22.         'Exception thrown: ' . date('F j, Y g:i:s a'),
  23.         $e->getMessage()
  24.     );
  25.  
  26.     // Clear the output buffer.
  27.     while( ob_end_clean() )
  28.     {
  29.     }
  30.  
  31.     // Output an error message.
  32.     echo 'The server made a boo-boo.  This should be your customized 500 error page.  You could even use include() here if you wanted.';
  33.  
  34.     // We're done here.
  35.     exit;
  36. }
  37.  
  38. ob_end_flush();
  39.  
Notice that even though the Exception gets thrown way down the stack in doQuery() [called by runABadQuery() called by main()], the Exception still gets caught.

In the code above, you can enclose the entirety of your code within a try/catch block, and if an Exception gets thrown *anywhere*, your code will stop, it will send an email with the text of the Exception to an administrator, and it will display a generic error page.

Note also that by using output buffering, you can prevent any output from reaching the browser until the script has successfully finished executing.
Oct 19 '07 #5
fjm
348 100+
Heya, Frank.

The main advantage to using try/catch is that you can catch Exceptions *anywhere*.

For example (and using the doQuery() function above):
Expand|Select|Wrap|Line Numbers
  1. function runABadQuery()
  2. {
  3. doQuery( 'this is not valid SQL' );
  4. }
  5.  
  6. ob_start();
  7.  
  8. try
  9. {
  10. echo 'You will never see this.';
  11.  
  12. runABadQuery();
  13.  
  14. echo 'You will never see this, either.';
  15. }
  16. catch( Exception $e )
  17. {
  18. // Alert admin
  19. mail
  20. (
  21. 'my@email.address',
  22. 'Exception thrown: ' . date('F j, Y g:i:s a'),
  23. $e->getMessage()
  24. );
  25.  
  26. // Clear the output buffer.
  27. while( ob_end_clean() )
  28. {
  29. }
  30.  
  31. // Output an error message.
  32. echo 'The server made a boo-boo. This should be your customized 500 error page. You could even use include() here if you wanted.';
  33.  
  34. // We're done here.
  35. exit;
  36. }
  37.  
  38. ob_end_flush();
  39.  
Notice that even though the Exception gets thrown way down the stack in doQuery() [called by runABadQuery() called by main()], the Exception still gets caught.

In the code above, you can enclose the entirety of your code within a try/catch block, and if an Exception gets thrown *anywhere*, your code will stop, it will send an email with the text of the Exception to an administrator, and it will display a generic error page.

Note also that by using output buffering, you can prevent any output from reaching the browser until the script has successfully finished executing.
Pbmods,

thanks for the great explanation. I am going to have to read php's docs on this exception error handling thingy to understand a little better how exactly I can implement this. You give a fantastic explanation but I am unfortunately, still a little lost. :)

I will sit on this for a couple of days and post back with my experiences. :)

Thanks bro!

Frank
Oct 19 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

13
by: Aggelos I. Orfanakos | last post by:
Hello. In a program, I want to ensure that a socket closes (so I use try ... finally), but I also want to catch/handle a socket exception. This is what I have done: try: try: s = ... #...
11
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses...
6
by: Daniel Wilson | last post by:
I am having exception-handling and stability problems with .NET. I will have a block of managed code inside try...catch and will still get a generic ..NET exception box that will tell me which...
7
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
3
by: Master of C++ | last post by:
Hi, I am an absolute newbie to Exception Handling, and I am trying to retrofit exception handling to a LOT of C++ code that I've written earlier. I am just looking for a bare-bones, low-tech...
19
by: KKramsch | last post by:
One of the features from other languages that I miss most in C is trappable exceptions. More specifically, I think it's great to be able to demarcate a whole block of code where several exceptions...
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
41
by: Zytan | last post by:
Ok something simple like int.Parse(string) can throw these exceptions: ArgumentNullException, FormatException, OverflowException I don't want my program to just crash on an exception, so I must...
2
by: Carol | last post by:
Exception may be thrown in the code inside the try block. I want to handling the SqlException with State == 1 in a special way, and for all others I want to use a general way to handle. Which of...
35
by: eliben | last post by:
Python provides a quite good and feature-complete exception handling mechanism for its programmers. This is good. But exceptions, like any complex construct, are difficult to use correctly,...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.