Dharani Saminathan
Dharani Saminathan

Reputation: 71

How to set custom exception handler in Laravel 5?

Hi I'm new to laravel and working with custom exception handling.

I have caught all exceptions known to my knowledge and it is working fine. As per my understanding, set_exception_handler is used for handling uncaught exceptions. Now I have two questions:

1) I have to know whether my understanding for set_exception_handler is correct or not.

2) How to implement it in laravel 5 to handle uncaught exceptions

This is how I have implemented set_exception_handler in my controller

class SearchController extends BaseController{

    public function getTitleMessage($exc){
        var_dump("set exception handler".$exc);
        return json_encode("Error");
    }

    public function genericSearch(){
       //Bussiness logic goes here

        set_exception_handler('getTitleMessage');
        throw new Exception("Search Failed");
    }

This is showing an error that set_exception_handler is not a valid callback. So I have changed my code to

set_exception_handler(array($this,'getTitleMessage'));

But also not working for me. Someone guide me how to implement it in laravel controller. Thanks in advance

Upvotes: 5

Views: 3458

Answers (2)

asmmahmud
asmmahmud

Reputation: 5044

You've to implement your custom exception handler logic in the app\Exceptions\Handler.php render method:

    public function render($request, Exception $exception) {
       if (method_exists($e, 'render') && $response = $e->render($request)){ 
             return Router::prepareResponse($request, $response);
        } elseif ($e instanceof Responsable) {
             return $e->toResponse($request);
        }
        $e = $this->prepareException($e);
       /* Your custom logic */
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } elseif ($e instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($e, $request);
        }
       return parent::render($request, $exception);
   }

Upvotes: 2

Moppo
Moppo

Reputation: 19275

Laravel already uses a global exception handler

Take a look at the vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php file; as you see in the bootstrap method, Laravel already uses set_exception_handler to set the handleException method as the global exception handler

That method will ultimately call App\Exceptions\Handler::render when an uncaught exception is raised.

So, if you want to handle in some way an exception that you're not catching manually, all you have to do is add your code to the render method:

app\Exceptions\Handler.php

public function render($request, Exception $e)
{
    //DO WATHEVER YOU WANT WITH $e

    return parent::render($request, $e);
}

Upvotes: 2

Related Questions