crmeb多商户二开crmeb架构二开文档异常处理【3】

异常处理

本着严谨的原则,框架会对任何错误(包括警告错误)抛出异常。系统产生的异常和错误都是程序的隐患,要尽早排除和解决,而不是掩盖。对于应用自己抛出的异常则做出相应的捕获处理。

不同模块处理调用相对异常处理类,详情见【CRMEB类库】->【Exceptions错误抛出】

可以整体所有应用定义统一异常处理类,app下或单独应用apiprovider.php注入绑定异常处理类
api应用下:

 
  1. // 容器Provider定义文件
  2. return [
  3. 'think\exception\Handle' => \app\api\ApiExceptionHandle::class,
  4. ];

自定义类需要继承think\exception\Handle并且实现render方法
如下完成类:

 
  1. <?php
  2. namespace app\api;
  3. use crmeb\exceptions\ApiException;
  4. use crmeb\exceptions\AuthException;
  5. use think\exception\DbException;
  6. use think\exception\Handle;
  7. use think\facade\Env;
  8. use think\Response;
  9. use Throwable;
  10. use think\exception\ValidateException;
  11. class ApiExceptionHandle extends Handle
  12. {
  13. /**
  14. * 记录异常信息(包括日志或者其它方式记录)
  15. *
  16. * @access public
  17. * @param Throwable $exception
  18. * @return void
  19. */
  20. public function report(Throwable $exception): void
  21. {
  22. // 使用内置的方式记录异常日志
  23. parent::report($exception);
  24. }
  25. /**
  26. * Render an exception into an HTTP response.
  27. *
  28. * @access public
  29. * @param \think\Request $request
  30. * @param Throwable $e
  31. * @return Response
  32. */
  33. public function render($request, Throwable $e): Response
  34. {
  35. // 添加自定义异常处理机制
  36. if ($e instanceof DbException) {
  37. return app('json')->fail('数据获取失败', [
  38. 'file' => $e->getFile(),
  39. 'message' => $e->getMessage(),
  40. 'line' => $e->getLine(),
  41. ]);
  42. } else if ($e instanceof AuthException || $e instanceof ApiException || $e instanceof ValidateException) {
  43. return app('json')->fail($e->getMessage());
  44. } else {
  45. return app('json')->fail('很抱歉!系统开小差了', Env::get('app_debug', false) ? [
  46. 'message' => $e->getMessage(),
  47. 'file' => $e->getFile(),
  48. 'code' => $e->getCode(),
  49. 'line' => $e->getLine(),
  50. 'trace' => $e->getTrace(),
  51. 'previous' => $e->getPrevious(),
  52. ] : []);
  53. }
  54. }
  55. }

手动捕获抛和出异常

可以手动使用throw来抛出一个异常

 
  1. // 使用think自带异常类抛出异常
  2. throw new \\think\\Exception('异常消息', 400);

手动捕获异常方式是使用try-catch

 
  1. try {
  2. // 这里是主体代码
  3. } catch (ValidateException $e) {
  4. // 这是进行验证异常捕获
  5. return json($e->getError());
  6. } catch (\Exception $e) {
  7. // 这是进行异常捕获
  8. return json($e->getMessage());
  9. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

crmeb专业二开

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值