Last active
September 5, 2017 16:41
-
-
Save ionutmilica/b7e07fa067fc91d0c0effc3b79ddd142 to your computer and use it in GitHub Desktop.
Using Laravel 5.5 render for exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class AuthService { | |
// ---- | |
public function issueToken(array $credentials) | |
{ | |
$token = $this->apiGuard()->attempt($credentials); | |
throw_if(!$token, InvalidCredentials::class); | |
$user = $this->apiGuard()->user(); | |
throw_if(!$user->confirmed, AccountNotConfirmed::class); | |
throw_if($user->suspended, AccountSuspended::class); | |
// Add more checks if needed | |
return $token; | |
} | |
private function apiGuard() | |
{ | |
return $this->auth->guard('api'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BaseError extends \Exception { | |
protected $code = 500; | |
protected $message = 'unknown error'; | |
protected $name = 'UNKNOWN_ERROR'; | |
/** | |
* Render exception to JSON | |
* | |
* @return \Illuminate\Http\JsonResponse | |
*/ | |
public function render() | |
{ | |
return response()->json([ | |
'name' => $this->name, | |
'message' => $this->message, | |
'code' => $this->code, | |
], $this->code); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class InvalidCredentials extends BaseError { | |
protected $code = 404; | |
protected $message = 'Invalid user credentials provided.'; | |
protected $name = 'INVALID_CREDENTIALS'; | |
} | |
class AccountNotConfirmed extends BaseError { | |
protected $code = 403; | |
protected $message = 'This account is not confirmed.'; | |
protected $name = 'ACCOUNT_NOT_CONFIRMED'; | |
} | |
class AccountSuspended extends BaseError { | |
protected $code = 403; | |
protected $message = 'This account is suspended.'; | |
protected $name = 'ACCOUNT_SUSPENDED'; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "ACCOUNT_NOT_CONFIRMED", | |
"message": "This account is not confirmed.", | |
"code": 403 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment