首先,我认为你的方法Sentry2UserRepository
还不错,没关系,IMO
。
问题1:将错误传递回控制器以便它知道要显示什么的正常/正确方法是什么?
好吧,IMO,根据应用程序,您应该确定应该如何处理异常。您提到so that it will know what to display
过,在这种情况下,这取决于您需要从异常中获取的信息以及在异常发生后采取下一步行动的方式和信息。现在,如果您需要错误消息,那么您可以返回,return $e->getMessage()
这样您就可以确切地知道实际发生了什么。有很多方法可以做到这一点,例如,使用单个catch
:
try{
// ...
}
catch( Exception $e )
{
if ($e instanceof UserNotFoundException) {
// it's an instance of UserNotFoundException, return accordingly
}
elseif ($e instanceof SomethinElseException) {
// it's an instance of SomethinElseException, return accordingly
}
}
此外,您可以使用不同的自定义异常类,并且可以使用多个catch
块,即
class AnException extends Exception
{
public function customErrorMessage()
{
return `AnException occurred!`
}
}
class AnotherException extends Exception
{
public function customErrorMessage()
{
return `AnotherException occurred!`
}
}
然后使用多个块捕获catch
,即
try
{
// ...
}
catch(AnException $e)
{
return $e->customErrorMessage();
}
catch(AnotherException $e)
{
return $e->customErrorMessage();
}
catch(Exception $e)
{
return $e->getMessage();
}
问题2:异常/错误是否有标准的json API格式?
问题 3:Web UI 使用内部 JsonApi 是一种好习惯吗?还是我现在使用 WebUi 控制器查询与 Api 相同的存储库以正确的方式做事?
其实我不知道这样的api
,你做对了,IMO。这是因为,你有这个
class Sentry2UserRepository implements UserInterface {
public function findById($id) {
try {
return Sentry::findUserById($id);
}
catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
// Do something here
return false;
}
}
}
因此,可以在控制器中编写类似这样的代码
if(findById(5)) {
// found and dump it to the view
}
else {
// show "Not Found !", false will be back only for UserNotFoundException
}
但是,如果你有这个在你的UserNotFoundException
捕获
return $e; // or anything else (maybe an array containing status and message)
那么这个简单的代码是不可能写出来的
if(findById(5)) {
// found and dump it to the view
}
因为,对于数组的对象 oe,is 语句将是真的$e
,所以你必须再次检查它,使用像这样的 somrthing
$result = findById(5);
if($result && $result->code && $result->code === 0) {
// something according to code
}
或者也许,像这样
if($result && $result->code) {
// error happened, now determine the code
switch($result->code){
case 0:
// show message
break;
case 1:
// show message
break;
}
}
所以,IMO,为什么,你需要向用户展示你的应用程序中发生了什么错误,为什么不只是状态,要么你得到数据,要么你没有得到它。是不是很简单?只是亲吻。这只是我的意见,仅此而已。