2
votes

I am writing an api for authorize users .

With my current code I can catch if response code is 200 however I cannot catch if the response is 401 instead of 200. Instead of an error message with my 401 response, I recieve error page.

this is my swagger server in Lumen

if($input['phone']==$this->phone && $input['password'] == $this->password){
            return response()->json([
            'redirect_uri' => $redirect_uri,
            'token' => $this->token 
            ]); 
        }

        return response()->json([
            'redirect_uri' => $redirect_uri,
            'errorMsg' => 'User Not found or id psw wrong'
            ],401); 

and this is my model in Laravel

if($response->getStatusCode() == 401){
            dd('you are not authorized');
        }

        if($response->getStatusCode() == 200){
            dd('you are authorized');
           //Store user credentials on cache
            CacheStore::storeUserCredentials(json_decode((string) $response->getBody(), true));
        }

basically if statuscode is 200 I recieve this message

enter image description here

But if status code is 401 it gives error.

enter image description here

2
How do you call the API?krisanalfa

2 Answers

1
votes

Apply try catch block to your code

try{
  // your api call
}
catch(Exception $e)
{
    if ($e instanceof HttpException && $e->getStatusCode()== 401)
    {
      dd('you are not authorized');
    }
}
1
votes

I recommend handling universal exceptions in app\Exceptions\Handler.php. In this file, there exists a render function.

To deal with different types of Exception, you can try:

public function render($request, Exception $e)
{
    if ($e instanceof SomeTypeException1)
    {
        #handle it
    }
    else if($e instanceof SomeTypeException2)
    {
        #handle it
    }

    return parent::render($request, $e);
}