I've been using PHP for quite a long time now, and I do enjoy it. 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.
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)
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