What is better way to deal error the my code?
Mosts developers learn write codes but forget importantly somethings as architecture, security… today we go talking about error and managing log is must importantly that you programmer know where and why occured error in your code and that you may solved fastly, the way that your application don’t expose intern errors for the users and compromisse the intregratidy it. To this case I will go use the PHP but leasson can extends to any languages programming that you using, let’s go.
Development Environment
To this example I create the simple script and use try catch to deal it. Basically you will throw the exception where occured error in the code. To this example I create the simple script and use try catch to deal it. All error will be thrown in the catch block and then do make that you need by example create log file with information error and define what comportament your application need to deal make it.
require '../vendor/autoload.php';
use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class Calculator
{
public function sum($a, $b)
{
try {
if(gettype($a) == 'integer' && gettype($b) == 'integer') return $a + $b;
throw new \Exception('error type data');
} catch(Exception $e) {
$log = new Logger('logger');
$log->pushHandler(new StreamHandler('../log/logger.log', Level::Error));
$log->error($e->getMessage());
// Display error to user
return 'Error while sum';
}
}
}
//Instance Class
$makeSum = new Calculator();
// Correct
echo $makeSum->sum(1,3);
// Error
echo $makeSum->sum('Hello World',3);
See that first you define the comportament intern this case we register the error on logger file and then display custom message to user without compromise integrity the application with intern errors, theese was some basically examples but with library Monolog you have many resources, can you create channel for receive the error some of channels is Slack, discord… and define error levels as error, warning, danger… see the official website to know all reasources.