lundi 5 octobre 2015

Laravel Exceptions Handler not work

Environment: Laravel 5.1, PHP 5.6.10

I tried to implement App\Exceptions\Handler::render() to response error message in JSON format.

The app/Exceptions/Handler.php as follows:

// ignore..

public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    } elseif ($e instanceof AbstractException) {
        return response()->apiJsonError(
                $e->getMessage(),
                $e->getErrors(),
                $e->statusCode());
    }

    // ignore...
}

In controller, it also throws an exception:

if (ArrayUtil::isIndexExceed($list, $maxIndex)) {
    // Index exceeds
    throw new App\Exceptions\ExceedingIndexException;
}

However, when the error occurs, the Handler::render() is not invoked. The response is the ExceedingIndexException stack.

The following part is Exception class

My custom exception class, ExceedingIndexException:

namespace App\Exceptions;

use App\Http\Responses\Error;
use App\Exceptions\AbstractException;

class ExceedingIndexException extends AbstractException
{
    public function __construct()
    {
        $message = 'Unable to execute';
        $error = new Error('exceeding_index_value');
        $statusCode = 400;

        parent::__construct($statusCode, $error, $message);
    }
}

The ExceedingIndexException class inherits AbstractException:

namespace App\Exceptions;

abstract class AbstractException extends \Exception
{
    protected $statusCode;
    protected $errors;

    public function __construct(
        $statusCode, $errors, $message, $code = 0, \Exception $previous = null) {
        parent::__construct($message, $code, $previous);

        $this->statusCode = $statusCode;
        $this->errors = $errors;
    }

    public function getStatusCode() 
    {
        return $this->statusCode;
    }

    public function getErrors() 
    {
        return $this->errors;
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire