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

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.

Related

Handle module not found in laravel 7 routing

let's say I have some
Route::get('/path/{model}', 'Controller#method');
In the case of mysite.com/path/1 & no Model#1, I getting 404 which is default Laravel behavior
I want to handle (basically, redirect to another named route) "NoModelFound" for specific group of routes / specific route
As this route exists, Route::fallback or Route::any will not trigger here.
I know there is a Route()->missing method in Laravel 8, but I have Laravel 7 and can't update.
Also, in the best way, I search for solutions within routes ( web.php )
Is any solution for this? thanks in advance
You can globally handle exception in App\Exceptions\Handler class. If you really and i mean really want to be specific about handling ModelNotFoundException for only certain routes then you can do some thing like
// Exception Handle class
public function render($request, Exception $exception)
{
if(
$request->is('*path/') && // or string match
$exception instanceof ModelNotFoundException
){
redirect()->to('where-ever');
}
}
If you just want to redirect user whenever ModelNotFoundException occurs then you could do this,
// Exception Handle class
public function render($request, Exception $exception)
{
if(
$exception instanceof ModelNotFoundException
){
redirect()->to('where-ever');
}
}
Another way would be to use a middleware and check for certain model, if it doesnt exist, then redirect the user. Depends on what you are trying to do. You can find more information here
https://laravel.com/docs/8.x/middleware
https://laravel.com/docs/8.x/errors#the-exception-handler

Laravel Spatie MultiTenanct noCurrentTenant Exception Handle

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.

Laravel: resource not found exception

Say you have a simple resource route like this:
Route::resource('overview', 'OverviewController');
And hit routes which you know don't exist. For example:
/overview/sdflkjdsflkjsd
/overview/sdflkjdsflkjsd/edit
Which in my case throws Trying to get property of non-object error from my view (as no resource is found)
I looked into adding 'Regular Expression Parameter Constraints' from the docs, but it looks like these are not available for resource routes either (plus don't really fix the problem).
I'm looking for a way to throw a single exception for this kind of thing, which I can then handle once, rather than add logic to each action (or at least the show and edit actions).. if possible.
EDIT After looking around github, I found the exception in the Symphony repo here. Is there a way I can hook into it?
Since you're getting a Trying to get property of non-object error, I assume you're fetching the resource via YourModel::find();
I'd suggest you use YourModel::findOrFail() instead. Then, you'd be getting a specific type of exception called ModelNotFoundException. Just register an error handler for this.
For instance,
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
UPDATE: This would actually go into render() method inside the app/Exceptions/Handler.php file in Laravel 5.1, and of course the code would utilize the passed $e parameter instead.
public function render($request, Exception $e)
{
if ($e instanceof ModelNotFoundException)
{
return \Response::make('Not Found', 404);
}
return parent::render($request, $e);
}

Laravel default route to 404 page

I'm using Laravel 4 framework and I've defined a whole bunch of routes, now I wonder for all the undefined urls, how to route them to 404 page?
In Laravel 5.2. Do nothing just create a file name 404.blade.php in the errors folder , it will detect 404 exception automatically.
Undefined routes fires the Symfony\Component\HttpKernel\Exception\NotFoundHttpException exception which you can handle in the app/start/global.php using the App::error() method like this:
/**
* 404 Errors
*/
App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception, $code)
{
// handle the exception and show view or redirect to a diff route
return View::make('errors.404');
});
The recommended method for handling errors can be found in the Laravel docs:
http://laravel.com/docs/4.2/errors#handling-404-errors
Use the App::missing() function in the start/global.php file in the following manner:
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
according to the official documentation
you can just add a file in: resources/views/errors/
called 404.blade.php with the information you want to display on a 404 error.
I've upgraded my laravel 4 codebase to Laravel 5, for anyone who cares:
App::missing(function($exception) {...});
is NO LONGER AVAILABLE in Laravel 5, in order to return the 404 view for all non-existent routes, try put the following in app/Http/Kernel.php:
public function handle($request) {
try {
return parent::handle($request);
}
catch (Exception $e) {
echo \View::make('frontend_pages.page_404');
exit;
// throw $e;
}
}

Laravel 4: redirect if item doesn't exists, ModelNotFoundException doesn't work anyway I try it

I'm following Dayle Rees' book "Code Bright" tutorial on building a basic app with Laravel (Playstation Game Collection).
So far so good, the app is working but, following his advices at the end of the chapter, I'm doing my homeworks trying to improve it
So, this snippet is working fine for existing models but throws an error if the item doesn't exists:
public function edit(Game $game){
return View::make('/games/edit', compact('game'));
}
In other words, http://laravel/games/edit/1 shows the item with ID = 1, but http://laravel/games/edit/21456 throws an error since there's no item with that ID
Let's improve this behaviour, adapting some scripts found also here on StackOverflow (Laravel 4: using controller to redirect page if post does not exist - tried but failed so far):
use Illuminate\Database\Eloquent\ModelNotFoundException; // top of the page
...
public function edit(Game $game){
try {
$current = Game::findOrFail($game->id);
return View::make('/games/edit', compact('game'));
} catch(ModelNotFoundException $e) {
return Redirect::action('GamesController#index');
}
}
Well... nothing happens! I still have the error with no redirect to the action 'GamesController#index'... and please notice that I have no namespaces in my Controller
I tried almost anything:
Replace catch(ModelNotFoundException $e) with catch(Illuminate\Database\Eloquent\ModelNotFoundException $e): no way
put use Illuminate\Database\Eloquent\ModelNotFoundException; in Model instead of Controller
Return a simple return 'fail'; instead of return Redirect::action('GamesController#index'); to see if the problem lies there
Put almost everywhere this snippet suggested in Laravel documentation
App::error(function(ModelNotFoundException $e)
{
return Response::make('Not Found', 404);
});
Well, simply nothing happened: my error is still there
Wanna see it? Here are the first two items in the errors stack:
http://www.iwstudio.it/laravelerrors/01.png
http://www.iwstudio.it/laravelerrors/02.png
Please, can someone tell me what am I missing? This is driving me mad...
Thanks in advance!
Here are few of my solutions:
First Solution
The most straightforward fix to your problem will be to use ->find() instead of ->findOrFail().
public function edit(Game $game){
// Using find will return NULL if not found instead of throwing exception
$current = Game::find($game->id);
// If NOT NULL, show view, ELSE Redirect away
return $current ? View::make('/games/edit', compact('game')) : Redirect::action('GamesController#index');
}
Second solution
As I notice you may have been using model binding to your route, according to Laravel Route model binding:
Note: If a matching model instance is not found in the database, a 404 error will be thrown.
So somewhere where you define the model binding, you can add your closure to handle the error:
Route::model('game', 'Game', function()
{
return Redirect::action('GamesController#index');
});
Third Solution
In your screenshot, your App::error seems to work as the error says HttpNotFound Exception which is Laravel's way of saying 404 error. So the last solution is to write your redirect there, though this apply globally (so highly discouraged).

Resources