I'm in the process of building a routing system for learning purposes and have encountered an issue which I think is a bit in the grey area of best practices. Can you guys help me decide if this is wrong, okay or could be done in a different way.
When resolving an incoming request and a route resource has been matched the HTTP request method is validated against the route's supported HTTP methods to ensure its capable of handling such requests. If this is not the case an exception of type UnsupportedMethodException
is thrown.
The HTTP status code documentation states that if a request method is denied/unsupported an Allow
header containing a list of supported methods should be returned in the response.
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
So to accommodate this I thought of extending the usage of the otherwise generic exception to require a sequential array of supported methods in its constructor.
class UnsupportedMethodException extends \RuntimeException {
/**
* A sequential array of supported HTTP request methods.
*
* @var array $supported
*/
private $supported = [];
/**
* @param string $message The typical exception message.
* @param array $supportedMethods A sequential array of HTTP request methods the matched route supports.
* @param \Exception $previous Any previous exceptions
*/
public function __construct($message, array $supportedMethods, \Exception $previous = null)
{
parent::__construct($message, null, $previous);
$this->supported = $supportedMethods;
}
/**
* @return array
*/
public function getSupportedMethods()
{
return $this->supported;
}
}
With the usage of type hinting the catch block provides I now have a solid method for fetching the supported methods and generating a proper HTTP response.
So my question is, do you guys think this is a good practice? Something tells me the exception class shouldn't contain such logic, but I have no proof/reference to back this up.