Saturday, April 16, 2022

Reactivity

Reactivity for DOM updates using e.g. Signals

Cloned templates for DOM rendering. Security issues using innerHTML.

Using APIs like <template> and Proxy: template.content.cloneNode(true)

Tuesday, April 5, 2022

Error handling in PHP

asdfasd

  1. $self = $this; // To use $this in closures
  2. set_error_handler(function ($en, $es, $ef, $el) use ($self) {
  3.     $self->error("Error #".$en, $es." (".$ef.":".$el.")");
  4. });
  5. set_exception_handler(function ($ex) use ($self) {
  6.     $self->error(get_class($ex), $ex->getMessage()." in ".$ex->getFile()." on line ".$ex->getLine(), $ex->getTrace());
  7. });

asdf

  1. private function error(string $heading, string $message = "", array $trace = null) { http_response_code(500); if ($_SERVER["HTTP_ACCEPT"] === "application/json") {
  2. exit($this->json([
  3. "status" => "error",
  4. "message" => $message,
  5. "trace" => $trace ?? debug_backtrace(0)
  6. ]));
  7. }
  8. $sTrace = ""; foreach ($trace ?? debug_backtrace(0) as $i => $exl) {
  9. if (isset($exl["file"])) {
  10. $sTrace .= "\n#".$i." ".$exl["file"]."(".$exl["line"]."): ".($exl["type"] ?? "").$exl["function"];
  11. }
  12. } exit("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>".$heading."</title><link rel=\"stylesheet\" href=\"error.css\"></head><body><h1>".$heading."</h1><p>".$message."</p><pre>".$sTrace."</pre></body></html>"); }

The produced trace string could look like this:

  1. #0 D:\Dev\PHP\quid\quid.php(170): ->error #1 D:\Dev\PHP\quid\tests\trace.php(99): ->{closure} #2 D:\Dev\PHP\quid\quid.php(239): ->test #3 D:\Dev\PHP\quid\quid.php(72): ->__construct

source code using $lines = file($errFile), I did further optimizations for certain scenarios, like with PDOException I don't need to see the code for get/set method in the PDO service, but rather where the query has been constructed. For this I simply iterate over stack trace and show first script, that differs from the last one. This obviously wouldn't work properly in other scenarios, so you should adjust the behavior to your situation.

asdf

<wbr> HTML element for breaking long paths on slashes

asdf

XDebug, breakpoints

  1. if ($this->debug && function_exists("xdebug_break")) {
  2. ("xdebug_break")(); // Intelephpsense error workaround
  3. }

doesn't work properly in set_error_handler, because the calls stacks starts there, not in the code that threw the exception.

asdf

Use master try-catch and try not use local, especially if it's silent. You will probably never know about the problem. If you use local, you should rethrow the exception.