简体   繁体   中英

How to register custom exception handler in laravel 8

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

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

i use this on laravel 8

    public function register()
    {

        $this->reportable(function (Throwable $e) {

        });

        $this->renderable(function (Throwable $e) {
            return $this->handleException($e);
        });
    }

Source : https://tony-stark.medium.com/laravel-8-error-handling-upgraded-2021-1ea9afcc2e95

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM