How can I handle NotFoundHttpException in Laravel 8?

Viewed 3027

I'm developing API in Laravel 8. I want to handle NotFoundHttpException to json response. But App\Exception\Handler updated in Laravel 8. By default render method does not exist. So I do not understand what I want to do. I have read in Laravel docs.

3 Answers

You can use a custom callback as per the documentation, App\Exceptions\Handler:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

public function register()
{
    $this->renderable(function (NotFoundHttpException $e, $request) {
        return response()->json(...);
    });
}

If you send the correct accept header with your request the exception handler will return a JSON response already though.

Laravel 8.x Docs - Error Handling - Rendering Exceptions

if you are running on Xamp , edit vhosts where lvauth is your project and directory name

DocumentRoot "C:\xampp\htdocs\lvauth\public" ServerAdmin lvauth Options Indexes FollowSymLinks AllowOverride All Require all granted

if you are running on Xamp , edit vhosts where lvauth is your project and directory name VirtualHost lv.auth:80 DocumentRoot "C:\xampp\htdocs\laravel\public" ServerAdmin lv.auth <Directory "C:\xampp\htdocs\laravel">enter image description here Options Indexes FollowSymLinks AllowOverride All Require all granted Directory VirtualHost

Related