How to register custom exception handler in laravel 8

Viewed 11928

In Laravel 7 this code works fine. Using renderable method also works in laravel 8. But I'm not sure how to register it in laravel 8 after creating a CustomException class.

    public function render($request, Exception $exception)
    {
        if ($exception instanceof ValidationException) {
            if ($request->expectsJson()) {
                return response('Sorry, validation failed.', 422);
            }
        }

        return parent::render($request, $exception);
    }
4 Answers

this worked for me.

The register method

   public function register()
   {
        $this->renderable(function(Exception $e, $request) {
            return $this->handleException($request, $e);
        });
    }

The content of handleException

 public function handleException($request, Exception $exception)
 {
     if($exception instanceof RouteNotFoundException) {
        return response('The specified URL cannot be  found.', 404);
     }
 }

I hope you will find it useful.

The documentation is a bit confusing to me too. Try this:

public function register()
{
    $this->renderable(function (ValidationException $e, $request) {
        if ($request->expectsJson()) {
           return response('Sorry, validation failed.', 422);
        }
    });
}

Try this

public function register()
{
    $this->renderable(function(\Illuminate\Validation\ValidationException $e, $request) {
        return response()->json([
            'result' => 1,
            'errors' => $e->errors()
        ], 200);
    });
}
Related