I am creating a RESTful API with Laravel. My API always returns JSON. What I would like to do is to maintain the logic of the answer in one place. Here's how I do it right now in the API controller that I'm pointing to Route::controller(). A nice and ultra-useful example:
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 will be, for example, an /double/13accessible GET method. The problem is that I repeat this attempt ... catch block in each method. I would like my API methods to be like this:
public function getDouble($number) {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
return $number;
}
And then, catch these exceptions and form the JSON elsewhere. What is the best approach in terms of a good application architecture?
source
share