Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace AppBundle\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ApiProblemException extends HttpException implements Exception
{
const TYPE_VALIDATION_ERROR = 'validation_error';
private static $titles = [
self::TYPE_VALIDATION_ERROR => 'There was a validation error.'
];
//
private $title;
private $extraData = array();
private $type;
public function __construct($statusCode, $type, \Exception $previous = null, array $headers = array(), $code = 0)
{
$this->setType($type);
parent::__construct($statusCode, $this->title, $previous, $headers, $code);
}
/**
* @param $name
* @param $value
*/
public function set($name, $value)
{
$this->extraData[$name] = $value;
}
/**
* @return array
*/
public function toArray()
{
return array_merge(
$this->extraData,
array(
'status' => $this->getStatusCode(),
'type' => $this->type,
'title' => $this->title
)
);
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @return null
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
*
* @throws \Exception
*/
public function setType($type)
{
if(!isset(self::$titles[$type])) {
throw new \Exception(sprintf('No title for "%s". Did you make it up?', $type));
}
$this->type = $type;
$this->title = self::$titles[$type];
}
public function buildResponse()
{
$response = new JsonResponse($this->toArray(), $this->getStatusCode());
$response->headers->set('Content-Type', 'application/problem+json');
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.