[英]How should I approach error handling in PHP? Specifically user input
I've been using PHP for quite a long time now, and I do enjoy it.我已经使用 PHP 很长时间了,我很喜欢它。 However, it has come to my attention that my error handling is not up to scratch and for the new project I am working on, I want to adopt a proper error-handling method.
然而,我注意到我的错误处理没有达到标准,对于我正在从事的新项目,我想采用适当的错误处理方法。
I'm wondering how to handle user input specifically, but also more generally any errors.我想知道如何专门处理用户输入,但更普遍的是任何错误。
I have a case as below as an example:我有一个例子如下:
function check_email($email){
if(empty($email)){
$error='You must enter an email address';
error_log($error);
header('Location: page.php?error='.$error);
exit();
}
if( *doesn't match regex* ){
$error='Not a valid email format';
error_log($error);
header('Location: page.php?error='.$error);
exit();
}
}
I want to both be able to revert to the user with the error message, and also log it in the error_log document.我希望既能够将错误消息还原给用户,又希望将其记录在 error_log 文档中。
The above method works fine, but it is super messy code, or at least it feels messy.上面的方法效果很好,但是代码超级乱,或者至少感觉很乱。 Any ideas how I can clean this up?
有什么想法可以清理吗? I want to be efficient with it because easy-to-write error catchers mean I will write more of them instead of being lazy
我想提高效率,因为易于编写的错误捕捉器意味着我会写更多而不是懒惰
Edit: yes, I could wrap that in a function of it's own编辑:是的,我可以将它包装在它自己的函数中
function er($error){
error_log($error);
header ('Location:...);
}
Surely there is a more elegant, native solution though?当然,有一个更优雅、更原生的解决方案吗?
I have utilised comments below to come up with two individual functions for soft errors and returning user errors我利用下面的评论提出了两个单独的函数来处理软错误和返回用户错误
For user errors:对于用户错误:
function return_error($msg){
$_SESSION['error']=$msg;
header("location:javascript://history.go(-1)");
exit;
}
For soft errors / unusual behaviour (make_file() function just makes a file if not exist)对于软错误/异常行为(如果不存在,make_file() 函数只会创建一个文件)
function soft_error($e){
$trace=debug_backtrace(-1);
if(isset($trace,$trace[0],$trace[0]['file'],$trace[0]['line'])){
$file=BASE_DIRECTORY.'logs/soft_error.log';
make_file($file);
$log=fopen($file,'a');
fwrite($log,'['.date('Y-m-d H:i:s').'] File: '.$trace[0]['file'].' - Line: '.$trace[0]['line'].' - Error: '.$e.PHP_EOL);
fclose($log);
}
}
For hard errors, there is error_log() or they will be logged automatically based on server settings, so that is fine对于硬错误,有 error_log() 或者它们将根据服务器设置自动记录,所以很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.