繁体   English   中英

使用http响应代码/消息指示重定向

[英]Using an http response code/message to dictate a redirect

我在下面调用一个API端点,并捕获直接从其返回的任何错误,将其解码并显示为错误:

try {
        $authService = new AuthService();
        $login = $authService->loginGetToken($email, $password);
    }catch (\Exception $e) {
        $response = json_decode($e->getResponse()->getBody()->getContents());
        $message = $response->message;

        return Redirect::back()->withErrors($message);
    }

我的问题:如果密码已过期,我会收到一条400错误消息,提示“密码已过期”

我的catch块中是否有一种方法可以检查代码和消息是否正确,如果是, auth.reset其重定向到auth.reset以重置密码?

您可以调用$e->getMessage() ... http://php.net/manual/zh/exception.getmessage.php ...还有一个$e->getCode()可以获取代码,因为您是都问了。

所以像这样:

if($e->getMessage() == 'Password is Expired') {
    return redirect('auth/reset'); // or whatever your route is
}

或使用您的代码:

try {
    ...
} catch (\Exception $) {
    $response = json_decode($e->getResponse()->getBody()->getContents());
    $message = $response->message;
    if($message == 'Password is Expired') {
        return redirect('auth/reset'); // or whatever your route is
    }
    return Redirect::back()->withErrors($message);
}

您可能还会发现,您正在获取一种特定类型的Exception,可以捕获:

catch (PasswordExpiredException $e) {
    ... // password is expired
} catch (Exception $e) {
    ... // something else happened
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM