Laravel Spatie MultiTenanct noCurrentTenant Exception Handle - laravel

I'm making a multitenancy system and I'm facing problem when trying to handle the NoCurrentTenant Exception..
I'm using spatie multitenancy
I'm expecting that when there is NoCurrentTenant exception is thrown , it should redirect to login route. But that is not happening.
Below is my Exception Hander register method.
public function register() {
$this->reportable(function (NoCurrentTenant $e) {
return redirect('/saml2/laraveltestidp/login');
});
}
But even after multiple tries it still shows below error only
Spatie\Multitenancy\Exceptions\NoCurrentTenant
The request expected a current tenant but none was set.

Related

How to handle Route Not Found Exception in Laravel 8 api?

I am using Laravel 8 and building API's. I have an issue am not able to handle Route Not found exception. I don't know how to handle in laravel 8.
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
Kindly help me.
If i type wrong url i face this error
[enter image description here][1]
But i want to display error message in response
[1]: https://i.stack.imgur.com/1qC9h.png
I found a fallback method for Route class in the documentation, it should satisfy what you need without using exceptions.
This is what is written in docs
Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request.
Route::fallback(function () {
return abort(404);
// return view('errors.404'); // incase you want to return view
});
There is also the method of extending the render method of exception handler but I guess this satisfies your needs.

Laravel passport custom error message and status code when user unauthorized

my project is running on Laravel 5.4 and I use passport to make authentication via api with bearer token. everything works fine, but when unauthorized user tries to reach resource that require authentication, the user gets error message 405 method not allowed
but I want response to be 401 unauthorized .
how can change this, and send only response with message, instead of exception? I did research, but couldn't find anything. I use standard laravel middleware for authorization auth:api. my routes grouped in middleware
Route::group(['middleware' => 'auth:api'], function () {
// these routes should return 401 if user not authenticated
}
Well method not allowed exception happens because you are hitting the wrong endpoint. You are posting to a get or vice verca.
However you can modify your exceptions if you go to App\Exception open up handler.php in render() method there you can adjust exceptions as you want example:
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return response('unauthorized', 401);
}
return parent::render($request, $exception);
}
On handler() method just check if $exception is instance of any exception object, if so you can modify the response as you want. For laravel exceptions follow link

prevent Lumen from showing default 500 Internal Server Error on API responses

I have a Route defined as:
$app->post('api/v1/Subject','SubjectController#createSubject');
And in the Controller I have the following code:
public function createSubject(Request $request){
$Subject = Subject::create($request->all());
return response()->json($Subject);
}
Now, when someone sends incorrect data, it triggers a Query Exception - "SQLSTATE[23000]: Integrity constraint violation:" which is understood.
However, what I want is: I want do not want Lumen to send its own default Error Page in API Response. I want to capture this error event and send my own customized response. How can I do that?
Since I could not find a solution, I tried to add my own view at: /resources/views/errors/500.blade.php but Lumen is even ignoring this template. Please help. Ideally, I would want to capture this error event and send my own customized response.
EDIT:
Lumen was reporting two exceptions - PDOException and QueryException at the 500 error response. So, to get a custom error message, I put the following code in side function render() in app\Exceptions\Handler:
public function render($request, Exception $e)
{
if($e instanceof PDOException){
return response('It is my Custom response for PDOException that caused 500 error response.');
}
if($e instanceof QueryException){
return response('It is my Custom response for QueryException that cuased 500 error response.');
}
return parent::render($request, $e);
}

Laravel return Csrf error as json

I'm building a mobile app and when a CSRF token isn't present I want to return an error in JSON instead of it returning the "TokenMismatchException" Html page.
Is there anyway to do this easily without adjusting the library code?
You can create your own custom responses and make one for TokenMismatchException
So you do that in the Exceptions/Handler.php file. Something like;
public function render($request, Exception $e)
{
if($e instanceof TokenMismatchException)
{
return json(......
}
I think you might also need to include in the use statement;
use Illuminate\Session\TokenMismatchException as TokenMismatchException;

how to handle laravel socialite "Missing authorization Exception"

In Laravel Socialite We are redirected to facebook. But When User Cancels (not allowing facebook to access public profile) it is giving error Missing Authorization exception
ClientException in RequestException.php line 107: Client error: GET
https://graph.facebook.com/oauth/access_token?client_id=1309844325833234&client_secret=1304bbdd28400tret49a295d324d577c&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fauth%2Ffacebook%2Fcallback`
resulted in a 400 Bad Request response: {"error":{"message":"Missing
authorization
code","type":"OAuthException","code":1,"fbtrace_id":"Aq9wMwG6ewl"}}
I dont want to display this Instead I Want to return to my site home page by giving a message "Facebook Login Failed" like what shown in stackoverflow facebook login.
Finally i got answer.Here it is
public function handleProviderCallback()
{
try {
$user = Socialite::driver('facebook')->user();
} catch (\Exception $e) {
//Here you can write excepion Handling Logic
}
}
Try catch didn't give good result to me. I used below methods to catch this error. If you're using Laravel Socialite library definitely it has function call handleProviderCallback. In that use this code
handleProviderCallback Method
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback()
{
$error_code = Input::get('error_code');
if ($error_code == 200)
{
return redirect()->route('sign-in')->with('error','You\'ve chose not to grant us permission to connect with your Facebook account.');
}
else
{
$fbUser = Socialite::driver('facebook')->user();
# rest of your code
}
}
Where does this error_code come from ??
Well, If you look at the error page(Laravel Black screened) come to you check the URL of that page. It has the these get methods error , error_code , error_description , error_reason , state.
Ex : http://localhost:8000/login/facebook/callback?error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied&state=mIxNjoDCogT2piMV5LX1Imk6GWNzqPUt3JZaqsIo#_=_
What I can do this to optimize this
You can use a switch statement based on error Check this Facebook error codes, with an error message and pass it.

Resources