MediaWiki master
HttpError.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Exception;
8
13
23class HttpError extends MWException {
25 private $httpCode;
27 private $header;
29 private $content;
30
39 public function __construct( $httpCode, $content, $header = null ) {
40 parent::__construct( (string)$content );
41 $this->httpCode = (int)$httpCode;
42 $this->header = $header;
43 $this->content = $content;
44 }
45
55 public function isLoggable() {
56 return false;
57 }
58
64 public function getStatusCode() {
65 return $this->httpCode;
66 }
67
73 public function report() {
74 $this->doLog();
75
76 HttpStatus::header( $this->httpCode );
77 header( 'Content-type: text/html; charset=utf-8' );
78 ContentSecurityPolicy::sendRestrictiveHeader();
79
80 print $this->getHTML();
81 }
82
83 private function doLog() {
84 $logger = LoggerFactory::getInstance( 'HttpError' );
85 $content = $this->content;
86
87 if ( $content instanceof Message ) {
88 $content = $content->text();
89 }
90
91 $context = [
92 'file' => $this->getFile(),
93 'line' => $this->getLine(),
94 'http_code' => $this->httpCode,
95 ];
96
97 $logMsg = "$content ({http_code}) from {file}:{line}";
98
99 if ( $this->getStatusCode() < 500 ) {
100 $logger->info( $logMsg, $context );
101 } else {
102 $logger->error( $logMsg, $context );
103 }
104 }
105
112 public function getHTML() {
113 if ( $this->header === null ) {
114 $titleHtml = htmlspecialchars( HttpStatus::getMessage( $this->httpCode ) );
115 } elseif ( $this->header instanceof Message ) {
116 $titleHtml = $this->header->escaped();
117 } else {
118 $titleHtml = htmlspecialchars( $this->header );
119 }
120
121 if ( $this->content instanceof Message ) {
122 $contentHtml = $this->content->escaped();
123 } else {
124 $contentHtml = nl2br( htmlspecialchars( $this->content ) );
125 }
126
127 return "<!DOCTYPE html>\n" .
128 "<html><head><title>$titleHtml</title><meta name=\"color-scheme\" content=\"light dark\" /></head>\n" .
129 "<body><h1>$titleHtml</h1><p>$contentHtml</p></body></html>\n";
130 }
131}
132
134class_alias( HttpError::class, 'HttpError' );
Show an error that looks like an HTTP server error.
Definition HttpError.php:23
report()
Report and log the HTTP error.
Definition HttpError.php:73
__construct( $httpCode, $content, $header=null)
Definition HttpError.php:39
getHTML()
Returns HTML for reporting the HTTP error.
getStatusCode()
Returns the HTTP status code supplied to the constructor.
Definition HttpError.php:64
isLoggable()
We don't want the default exception logging as we got our own logging set up in self::report.
Definition HttpError.php:55
Create PSR-3 logger objects.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:144
text()
Returns the message text.
Definition Message.php:1135
Handle sending Content-Security-Policy headers.