我正在用Laravel构建RESTful API。我的API总是返回JSON。我想做的是将响应逻辑保持在一个位置。以下是我现在在API控制器中的操作方式,Route::controller()
指出了这一点。有趣和非常有用的例子来了:
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);
}
在本例中,例如,我的API路由是由GET方法访问的/double/13
。问题是我重复这个尝试。。。每个方法中的catch块。我希望我的API方法是这样的:
public function getDouble($number) {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
return $number;
}
然后,捕获这些异常并在另一个地方形成JSON。就良好的应用程序体系结构而言,什么是最好的方法?
异常响应
您可以通过在App'Exceptions'Handler
中处理异常来完成此操作。
你可以在渲染方法中完成,比如:
/**
* Render an exception into an HTTP response.
*
* @param 'Illuminate'Http'Request $request
* @param 'Exception $e
* @return 'Illuminate'Http'Response
*/
public function render($request, Exception $e)
{
if($e instanceof HttpException) {
return response()->json($e->getMessage(), $e->getStatusCode());
}
return parent::render($request, $e);
}
成功响应
有几种方法可以做到这一点,但我想中间件将是最合适的一种。
- 创建一个中间件(比如ApiResponseFormatterMiddleware)
- 在"App''Http''Kernel"中,将其添加到
$routeMiddleware
数组中 - 将其应用于要解析的api路由、响应
你可以做一些类似的事情:
/**
* Handle an incoming request.
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return response()->json($response->getOriginalContent());
}
当然,您需要更改一些逻辑,以按照您想要的方式解析内容,但骨架保持不变。