Skip to content

Instantly share code, notes, and snippets.

@ionutmilica
Last active September 5, 2017 16:41
Show Gist options
  • Save ionutmilica/b7e07fa067fc91d0c0effc3b79ddd142 to your computer and use it in GitHub Desktop.
Save ionutmilica/b7e07fa067fc91d0c0effc3b79ddd142 to your computer and use it in GitHub Desktop.
Using Laravel 5.5 render for exceptions
<?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');
}
}
<?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);
}
}
<?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';
}
{
"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