public function report(Exception $exception)
{
if (app()->bound('sentry') && $this->shouldReport($exception)) {
app('sentry')->captureException($exception);
}
parent::report($exception);
}
还有默认的渲染方法在表单验证时生成响应的JSON格式往往跟我们项目里统一的JOSN格式不一样这就需要我们自定义渲染方法的行为。
public function render($request, Exception $exception)
{
//如果客户端预期的是JSON响应, 在API请求未通过Validator验证抛出ValidationException后
//这里来定制返回给客户端的响应.
if ($exception instanceof ValidationException && $request->expectsJson()) {
return $this->error(422, $exception->errors());
}
if ($exception instanceof ModelNotFoundException && $request->expectsJson()) {
//捕获路由模型绑定在数据库中找不到模型后抛出的NotFoundHttpException
return $this->error(424, 'resource not found.');
}
if ($exception instanceof AuthorizationException) {
//捕获不符合权限时抛出的 AuthorizationException
return $this->error(403, "Permission does not exist.");
}
return parent::render($request, $exception);
}
自定义后,在请求未通过FormValidator验证时会抛出ValidationException, 之后异常处理器捕获到异常后会把错误提示格式化为项目统一的JSON响应格式并输出给客户端。这样在我们的控制器中就完全省略了判断表单验证是否通过如果不通过再输出错误响应给客户端的逻辑了,将这部分逻辑交给了统一的异常处理器来执行能让控制器方法瘦身不少。
使用自定义异常
这部分内容其实不是针对Laravel框架自定义异常,在任何项目中都可以应用我这里说的自定义异常。
我见过很多人在Repository或者Service类的方法中会根据不同错误返回不同的数组,里面包含着响应的错误码和错误信息,这么做当然是可以满足开发需求的,但是并不能记录发生异常时的应用的运行时上下文,发生错误时没办法记录到上下文信息就非常不利于开发者进行问题定位。
下面的是一个自定义的异常类
namespace App\Exceptions\;
use RuntimeException;
use Throwable;
class UserManageException extends RuntimeException
{
/**
* The primitive arguments that triggered this exception
*
* @var array
*/
public $primitives;
/**
* QueueManageException constructor.
* @param array $primitives
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct(array $primitives, $message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->primitives = $primitives;
}
/**
* get the primitive arguments that triggered this exception
*/
public function getPrimitives()
{
return $this->primitives;
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
