接口(interface)调用
http://localhost:8888/api/v1/users/100 //doesn't exist
html调用
http://localhost:8888/admin/users/100 //doesn't exist
显然,我不希望 Html Call 异常返回 json 数据,也不希望 Api Call 返回 Html 数据。
我不是 Controller 中的异常处理。我在我的 UserRepository 中处理异常。因此,我的 Controller 只是从用户存储库返回结果。
class Sentry2UserRepository implements UserInterface {
public function findById($id) {
try {
return Sentry::findUserById($id);
}
catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
// Do something here
return false;
}
}
}
问题 1:将错误传递回 Controller 以便它知道要显示什么的正常/正确方法是什么?
问题 2:异常/错误是否有标准的 json API 格式?
问题 3:Web UI 使用内部 JsonApi 是一种好习惯吗?或者我现在使用 WebUi Controller 查询与 Api 相同的存储库是否以正确的方式做事?
最佳答案
在你的 filters.php 中试试这个魔法:
App::error(function(Exception $exception, $httpCode)
{
if (Request::is('api/*')){
return Response::json( ['code' => $exception->getCode(), 'error' => $exception->getMessage()], $httpCode );
}else{
$layout = View::make('layouts.main');
$layout->content = View::make('errors.error')->with('code', $exception->getCode())->with('error', $exception->getMessage())->with('httpCode',$httpCode);
return Response::make($layout, $httpCode);
}
});
关于exception-handling - Laravel 异常处理 - 如何使用 API 和 Html 处理异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19103905/