【发布时间】:2015-10-06 06:36:14
【问题描述】:
环境:Laravel 5.1、PHP 5.6.10
我尝试实现App\Exceptions\Handler::render() 以响应 JSON 格式的错误消息。
app/Exceptions/Handler.php如下:
// 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...
}
在控制器中,也抛出异常:
if (ArrayUtil::isIndexExceed($list, $maxIndex)) {
// Index exceeds
throw new App\Exceptions\ExceedingIndexException;
}
但是,当错误发生时,不会调用 Handler::render()。响应是ExceedingIndexException 堆栈。
以下部分为异常类
我的自定义异常类,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);
}
}
ExceedingIndexException 类继承 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;
}
}
解决方案
我发现我的项目依赖于 Dingo API for RESTful API。因为,Dingo 也支持并注册了自己的异常处理程序,App\Exceptions\Handler 不会被调用。
我尝试使用Custom Exception Responses in Dingo API 作为我的异常处理程序来响应 JSON 格式的错误。它对我有用。
【问题讨论】:
-
我认为这个问题与您位于控制器内部的
ExceedingIndexException无关。除了ModelNotFoundException触发AbstractException之前应该发生什么错误?
标签: php laravel exception laravel-5.1