MediaWiki master
HttpError.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Exception;
22
26
36class HttpError extends MWException {
38 private $httpCode;
40 private $header;
42 private $content;
43
52 public function __construct( $httpCode, $content, $header = null ) {
53 parent::__construct( (string)$content );
54 $this->httpCode = (int)$httpCode;
55 $this->header = $header;
56 $this->content = $content;
57 }
58
68 public function isLoggable() {
69 return false;
70 }
71
77 public function getStatusCode() {
78 return $this->httpCode;
79 }
80
86 public function report() {
87 $this->doLog();
88
89 HttpStatus::header( $this->httpCode );
90 header( 'Content-type: text/html; charset=utf-8' );
91
92 print $this->getHTML();
93 }
94
95 private function doLog() {
96 $logger = LoggerFactory::getInstance( 'HttpError' );
97 $content = $this->content;
98
99 if ( $content instanceof Message ) {
100 $content = $content->text();
101 }
102
103 $context = [
104 'file' => $this->getFile(),
105 'line' => $this->getLine(),
106 'http_code' => $this->httpCode,
107 ];
108
109 $logMsg = "$content ({http_code}) from {file}:{line}";
110
111 if ( $this->getStatusCode() < 500 ) {
112 $logger->info( $logMsg, $context );
113 } else {
114 $logger->error( $logMsg, $context );
115 }
116 }
117
124 public function getHTML() {
125 if ( $this->header === null ) {
126 $titleHtml = htmlspecialchars( HttpStatus::getMessage( $this->httpCode ) );
127 } elseif ( $this->header instanceof Message ) {
128 $titleHtml = $this->header->escaped();
129 } else {
130 $titleHtml = htmlspecialchars( $this->header );
131 }
132
133 if ( $this->content instanceof Message ) {
134 $contentHtml = $this->content->escaped();
135 } else {
136 $contentHtml = nl2br( htmlspecialchars( $this->content ) );
137 }
138
139 return "<!DOCTYPE html>\n" .
140 "<html><head><title>$titleHtml</title><meta name=\"color-scheme\" content=\"light dark\" /></head>\n" .
141 "<body><h1>$titleHtml</h1><p>$contentHtml</p></body></html>\n";
142 }
143}
144
146class_alias( HttpError::class, 'HttpError' );
getFile()
Get the file for this page, if one exists.
Show an error that looks like an HTTP server error.
Definition HttpError.php:36
report()
Report and log the HTTP error.
Definition HttpError.php:86
__construct( $httpCode, $content, $header=null)
Definition HttpError.php:52
getHTML()
Returns HTML for reporting the HTTP error.
getStatusCode()
Returns the HTTP status code supplied to the constructor.
Definition HttpError.php:77
isLoggable()
We don't want the default exception logging as we got our own logging set up in self::report.
Definition HttpError.php:68
Create PSR-3 logger objects.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:157
text()
Returns the message text.
Definition Message.php:1150