As I understand processData()
returns the response object in case of any errors occur, but returns another type of data otherwise. This means this method is returning two different types of data in different situations, so in your controller you need to handle its return value differently: if it is returning a response object, you can return it as is, but if it returns the processed data, you need to return a json response built using that data...this makes things a little confusing.
Your idea about throwing an error seems fine, and you should know you can (and you must) return a proper response in case of any error. That is why a Slim error handler should return a response object.
To refactor your code, I see these options:
- Throw an exception in
processData()
and define some custom exception classes and write a good error handler to produce the correct error response (recommended)
private function processData(ResponseInterface $response)
{
...
$error = true; // simulate error
if($error){
throw new DataProcessingException('Details about why this happened');
}
return $processedData;
}
// in your controller
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args)
{
$someData = ...;
$processedData = $this->processData($someData, $response);
return $response->withJson($processedData);
}
// in error handler
...
catch (\DataProcessingException $e) {
return $response->withJson(['error' => 'A data processing exception has occurred', 'details' => $e->getMessage()], 500);
}
- Throw an exception in
processData()
on any error and handle it in controller:
private function processData(ResponseInterface $response)
{
...
$error = true; // simulate error
if($error){
throw new \Exception('error message');
}
return $processedData;
}
// in your controller
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args)
{
$someData = ...;
try {
$processedData = $this->processData($someData, $response);
return $response->withJson($processedData);
}
catch (\Exception $e) {
return $response->withJson('error', 500);
}
}
- In
processData()
, return $processedData
or some value (FALSE
for example) to indicate an error, and in controller, generate a corresponding response (not recommended):
private function processData(ResponseInterface $response)
{
...
$error = true; // simulate error
if($error){
return false;
}
return $processedData;
}
// in your controller
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args)
{
$someData = ...;
$processedData = $this->processData($someData, $response);
if ($processedData === false) {
return $response->withJson('error', 500);
}
return $response->withJson($processedData);
}