Laravel中的AppExceptionsHandler 类负责记录应用程序触发的所有异常,这在我们开发过程中十分方便,总是try...catch使代码太过繁琐且可读性大大降低,那么怎么使用它处理异常为json呢?
方法如下:
我们可以新建一个class,用来处理异常返回。 - <?php
- /**
- * Author: sai
- * Date: 2020/1/15
- * Time: 14:31
- */
- namespace App\Exceptions;
- class ApiException extends \Exception
- {
- const ERROR_CODE = 1001;
- const ERROR_MSG = 'ApiException';
- private $data = [];
- /**
- * BusinessException constructor.
- *
- * @param string $message
- * @param string $code
- * @param array $data
- */
- public function __construct(string $message, string $code, $data = [])
- {
- $this->code = $code ? : self::ERROR_CODE;
- $this->message = $message ? : self::ERROR_MSG;
- $this->data = $data;
- }
- /**
- * @return array
- */
- public function getData()
- {
- return $this->data;
- }
- /**
- * 异常输出
- */
- public function render($request)
- {
- return response()->json([
- 'data' => $this->getData(),
- 'code' => $this->getCode(),
- 'messgae' => $this->getMessage(),
- ], 200);
- }
- }
复制代码然后我们在Handler加入,加入$dontReport,便不会使用自带的错误处理,而使用自定义的处理。 - <?php
- namespace App\Exceptions;
- use Exception;
- use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
- class Handler extends ExceptionHandler
- {
- /**
- * 一些不需管或不需要抛出的异常
- */
- protected $dontReport = [
- ApiException::class,
- ];
- ...
- }
复制代码我们测试一下: - <?php
- namespace App\Http\Controllers;
- use App\Exceptions\ApiException;
- use Illuminate\Http\Request;
- class HomeController extends Controller
- {
- public function index(Request $request)
- {
- throw new ApiException('error', 10001, ['oh' => 'no']);
- return 1;
- }
- }
复制代码查看输出:
测试ok,我们可以愉快的使用啦。当然,其他形式的错误输出可以自行扩展。
总结
到此这篇关于Laravel统一错误处理为JSON的文章就介绍到这了,更多相关Laravel统一错误处理为JSON内容请搜索晓枫资讯以前的文章或继续浏览下面的相关文章希望大家以后多多支持晓枫资讯!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |