Laravel9 自定义异常处理(2)
再学习Laravel9的时候,需要处理一些异常错误
如下
1、自定义的异常或者是编码者已知的异常:权限不足|密码错误|递归死循环|TOKEN过期
throw new \App\Exceptions\BusinessException(400, ‘密码错误’);
2、未知异常
类不存、方法不存在、语法错误、数据SQL语句错误等等,这类异常通过给你报一屏的错误,我说的是一屏,很不友好,有时候影响前端的显示。
在项目实施中,我是这样做的:
自定义的异常
App\Exceptions\目录下,新建BusinessException.php,
代码:
<?php
namespace App\Exceptions;
use Exception;
class BusinessException extends Exception
{
protected $code;
protected $message;
public function __construct($code, $message)
{
$this->code = $code ?: 400;
$this->message = $message;
}
/**
* 渲染异常为 HTTP 响应。
*/
public function render()
{
return response()->json([
"msg" => $this->message,
"code" => $this->code ?: 400,
"data" => '',
]);
}
}
App\Exceptions\handle.php 增加方法
// 将异常信息响应给客户端
public function render($request, Throwable $exception)
{
// 检查异常类型:BusinessException的时候执行
if ($exception instanceof \App\Exceptions\BusinessException) {
return $exception->render();
}
$statusCode = $exception->getCode() ?: Response::HTTP_BAD_REQUEST;
// 返回自定义响应,例如 JSON 错误响应
return response()->json([
'msg' => $exception->getMessage(),
'code' => $statusCode,
'data' => '',
]);
// // 在这里处理你想要处理的异常,并返回响应
return parent::render($request, $exception);
}
这段方法的功能有两个:检测到异常类型:BusinessException的时候执行App\Exceptions\BusinessException的render()方法,否则,就按照API自定义开发的格式输出错误,我们把错误信息放在了msg里面,我们查看或者反馈给前端的错误信息,而不是一屏直接报错。亲测,很好拦截了SQL的错误。
以上内容,仅供新手学习。
我希望的是错误信息能提示具体行数,看哪位大佬可以提供下解决方案。
本作品采用《CC 协议》,转载必须注明作者和本文链接
这个异常信息其实是给开发人员看的,你直接输出客户端,对用户而言是不友好的