I'm building RESTful API with Laravel. My API always returns JSON. What I would like to do, is keeping response logic at one place. Here's how I do it right now in API controller, which is pointed to by Route::controller()
. Funny and ultra-useful example coming:
public function getDouble($number) {
try {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
$response = $number * 2;
$status = 200;
}
catch (HttpException $exception) {
$response = $exception->getMessage();
$status = $exception->getStatusCode();
}
return response()->json($response, $status);
}
In this example, my API route would be for example /double/13
accessed by GET method. The problem is that I repeat this try ... catch block in each method. I would like my API methods to be like:
public function getDouble($number) {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
return $number;
}
And then, catch those exceptions and form JSON in another place. What is the best approach here in terms of good application architecture?