2016-08-19 00:51:35 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace SilverStripe\Control;
|
|
|
|
|
|
|
|
use Exception;
|
|
|
|
|
|
|
|
/**
|
2016-09-09 08:43:05 +02:00
|
|
|
* A {@link HTTPResponse} encapsulated in an exception, which can interrupt the processing flow and be caught by the
|
2016-08-19 00:51:35 +02:00
|
|
|
* {@link RequestHandler} and returned to the user.
|
|
|
|
*
|
|
|
|
* Example Usage:
|
|
|
|
* <code>
|
2016-09-09 08:43:05 +02:00
|
|
|
* throw new HTTPResponse_Exception('This request was invalid.', 400);
|
|
|
|
* throw new HTTPResponse_Exception(new HTTPResponse('There was an internal server error.', 500));
|
2016-08-19 00:51:35 +02:00
|
|
|
* </code>
|
|
|
|
*/
|
2016-09-09 08:43:05 +02:00
|
|
|
class HTTPResponse_Exception extends Exception
|
2016-08-19 00:51:35 +02:00
|
|
|
{
|
|
|
|
|
|
|
|
protected $response;
|
|
|
|
|
|
|
|
/**
|
2016-09-09 08:43:05 +02:00
|
|
|
* @param HTTPResponse|string $body Either the plaintext content of the error
|
|
|
|
* message, or an HTTPResponse object representing it. In either case, the
|
2016-08-19 00:51:35 +02:00
|
|
|
* $statusCode and $statusDescription will be the HTTP status of the resulting
|
|
|
|
* response.
|
|
|
|
* @param int $statusCode
|
|
|
|
* @param string $statusDescription
|
2016-09-09 08:43:05 +02:00
|
|
|
* @see HTTPResponse::__construct();
|
2016-08-19 00:51:35 +02:00
|
|
|
*/
|
|
|
|
public function __construct($body = null, $statusCode = null, $statusDescription = null)
|
|
|
|
{
|
2016-09-09 08:43:05 +02:00
|
|
|
if ($body instanceof HTTPResponse) {
|
2016-08-19 00:51:35 +02:00
|
|
|
// statusCode and statusDescription should override whatever is passed in the body
|
|
|
|
if ($statusCode) {
|
|
|
|
$body->setStatusCode($statusCode);
|
|
|
|
}
|
|
|
|
if ($statusDescription) {
|
|
|
|
$body->setStatusDescription($statusDescription);
|
|
|
|
}
|
|
|
|
|
|
|
|
$this->setResponse($body);
|
|
|
|
} else {
|
2016-09-09 08:43:05 +02:00
|
|
|
$response = new HTTPResponse($body, $statusCode, $statusDescription);
|
2016-08-19 00:51:35 +02:00
|
|
|
|
|
|
|
// Error responses should always be considered plaintext, for security reasons
|
|
|
|
$response->addHeader('Content-Type', 'text/plain');
|
|
|
|
|
|
|
|
$this->setResponse($response);
|
|
|
|
}
|
|
|
|
|
|
|
|
parent::__construct($this->getResponse()->getBody(), $this->getResponse()->getStatusCode());
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-09-09 08:43:05 +02:00
|
|
|
* @return HTTPResponse
|
2016-08-19 00:51:35 +02:00
|
|
|
*/
|
|
|
|
public function getResponse()
|
|
|
|
{
|
|
|
|
return $this->response;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-09-09 08:43:05 +02:00
|
|
|
* @param HTTPResponse $response
|
2016-08-19 00:51:35 +02:00
|
|
|
*/
|
2016-09-09 08:43:05 +02:00
|
|
|
public function setResponse(HTTPResponse $response)
|
2016-08-19 00:51:35 +02:00
|
|
|
{
|
|
|
|
$this->response = $response;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|