Laravel return Csrf error as json - validation

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;

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.

How to redirect another page instead of redirecting to abort 403 error page in Laravel 5.4

My question is whenever there is a 403 error I should redirect to my own custom page or show the flash message(on the same page) something like that.How can I achieve this in Laravel?.
You can use app/Exceptions/Handler.php for this
public function render($request, Exception $e)
{
if ($e->getStatusCode() == 403) {
return redirect('yourpage'); // this will be on a 403 exception
}
return parent::render($request, $e); // all the other exceptions
}
You can create a view for specific HTTP error codes. If you set up a Blade template at resources/views/errors/403.blade.php, it will get used for all 403 error responses.
Source
Alternatively you can set up a custom exception handler for 403 responses if you need something more involved. I found a good example of this here.
you can make you own page in inside the view .resources/views/errors/yourblade.blade.php
after that just return your page to that page.
You can use app/Exceptions/Handler.php for this as Thomas Moors stated above or you can use a try catch for basic error handling.
try {
do Something //
}
catch (Exception $e) {
//log error in log file or dv
return redirect->('home');
}

Design 500 error page only for production

I'm looking for a modern (Laravel 5.4) way to display custom 500 error page only for HTTP (non ajax/fetch) response. I read some threads but each response looks like a trick or is outdated. There is probably something to modify in \App\Exceptions\Handler, but I did not find the "right way".
Is there a simple way to display a specific page on fatal error (uncatched, returning 500) in Laravel 5.4?
In other words, when I have a syntax error on one of my controller, it displays "Whoops something went wrong" with some HTML and 500 error code. I would like to display something else, with the same rules as default behavior (ideally only for HTML browser, not for ajax/fetch, etc.).
EDIT: only in production environment.
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable.
https://laravel.com/docs/5.4/errors#custom-http-error-pages
From the selected "best answer" of this thread: https://laracasts.com/discuss/channels/general-discussion/custom-error-page-er500
You could modify \App\Exceptions\Handler::render():
public function render($request, Exception $exception)
{
if (config('app.debug') && !$this->isHttpException($exception)) {
$exception = new \Symfony\Component\HttpKernel\Exception\HttpException(500);
}
return parent::render($request, $exception);
}
Your exception will be reported in the logs as usually, but woops page will be replaced by your 500.blade.php view.
Sometimes you have to catch the specific exception in order to render the error view. in Laravel 5.4 you can do this by editing the report() method in the App\Exceptions\Handler class
public function report(Exception $exception)
{
if ($exception instanceof CustomException) {
// here you can log the error and return the view, redirect, etc...
}
return parent::report($exception);
}

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);
}

Creating custom error page in Lumen

How do I create custom view for errors on Lumen? I tried to create resources/views/errors/404.blade.php, like what we can do in Laravel 5, but it doesn't work.
Errors are handled within App\Exceptions\Handler. To display a 404 page change the render() method to this:
public function render($request, Exception $e)
{
if($e instanceof NotFoundHttpException){
return response(view('errors.404'), 404);
}
return parent::render($request, $e);
}
And add this in the top of the Handler.php file:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Edit: As #YiJiang points out, the response should not only return the 404 view but also contain the correct status code. Therefore view() should be wrapped in a response() call passing in 404 as status code. Like in the edited code above.
The answer by lukasgeiter is almost correct, but the response made with the view function will always carry the 200 HTTP status code, which is problematic for crawlers or any user agent that relies on it.
The Lumen documentation tries to address this, but the code given does not work because it is copied from Laravel's, and Lumen's stripped down version of the ResponseFactory class is missing the view method.
This is the code which I'm currently using.
use Symfony\Component\HttpKernel\Exception\HttpException;
[...]
public function render($request, Exception $e)
{
if ($e instanceof HttpException) {
$status = $e->getStatusCode();
if (view()->exists("errors.$status")) {
return response(view("errors.$status"), $status);
}
}
if (env('APP_DEBUG')) {
return parent::render($request, $e);
} else {
return response(view("errors.500"), 500);
}
}
This assumes you have your errors stored in the errors directory under your views.
It didn't work for me, but I got it working with:
if($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
return view('errors.404');
}
You might also want to add
http_response_code(404)
to tell the search engines about the status of the page.

Resources