php中除了常见的try/catch,error_reporting()之外,还提供了set_error_handler()函数用于自定义错误处理函数。
php默认的错误处理是直接在页面上打印错误信息,例如:
Warning: mkdir() [function.mkdir]: Permission denied in /usr/local/light/htdocs/a.php on line 2 Warning: chdir() [function.chdir]: No such file or directory (errno 2) in /usr/local/light/htdocs/d.php on line 30
而上述的返回信息是以200的http code返回的,这样就给RESTful应用带来困扰。通过set_error_handler可以很好的解决这个问题,捕捉所有错误,然后对于严重的错误给出500的http返回码,指示客户端做出相应的响应。 <pre class=php name=code> function ErrorHandler($errno, $errstr, $errfile, $errline) { switch($errno){ case E_ERROR: $err = “Error”; break; case E_WARNING: $err = “Warning”; break; case E_CORE_ERROR: $err = “Core Error”; break; case E_USER_ERROR: $err = “User Error”; break; case E_COMPILE_ERROR: $err = “Compile Error”; break; case E_PARSE: $err = “Parse Error”; break;
case E_NOTICE: $err = "Notice";
case E_CORE_WARNING: $err = "Core Warning";
case E_COMPILE_WARNING: $err = "Compile Warning";
case E_USER_WARNING: $err = "User Warning";
case E_USER_NOTICE: $err = "User Notice";
case E_STRICT: $err = "Strict Notice";
case E_RECOVERABLE_ERROR: $err = "Recoverable Error";
default: $err = "Unknown error ($errno)";
return true;
}
header("HTTP/1.1 500 Internal Server Error");
echo 'Internal Server Error: '."$errno:$err".'<br/>';
echo 'msg: '.$errstr.'<br/>';
runlog("catch error($errno:$err:$errstr), $errfile:$errline");
die(); } set_error_handler("ErrorHandler");</pre>