ExceptionHandle.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace app;
  3. use crmeb\services\wechat\WechatException;
  4. use qiniu\exceptions\AdminException;
  5. use qiniu\exceptions\UploadException;
  6. use qiniu\exceptions\PayException;
  7. use qiniu\exceptions\ApiException;
  8. use qiniu\exceptions\TemplateException;
  9. use qiniu\exceptions\AuthException;
  10. use think\db\exception\DataNotFoundException;
  11. use think\db\exception\DbException;
  12. use think\db\exception\ModelNotFoundException;
  13. use think\exception\Handle;
  14. use think\exception\HttpException;
  15. use think\exception\HttpResponseException;
  16. use think\exception\ValidateException;
  17. use think\facade\Env;
  18. use think\Response;
  19. use Throwable;
  20. /**
  21. * 应用异常处理类
  22. */
  23. class ExceptionHandle extends Handle
  24. {
  25. /**
  26. * 不需要记录信息(日志)的异常类列表
  27. * @var array
  28. */
  29. protected $ignoreReport = [
  30. HttpException::class,
  31. HttpResponseException::class,
  32. ModelNotFoundException::class,
  33. DataNotFoundException::class,
  34. ValidateException::class,
  35. AdminException::class,
  36. UploadException::class,
  37. PayException::class,
  38. ApiException::class,
  39. TemplateException::class,
  40. AuthException::class
  41. ];
  42. /**
  43. * 记录异常信息(包括日志或者其它方式记录)
  44. *
  45. * @access public
  46. * @param Throwable $exception
  47. * @return void
  48. */
  49. public function report(Throwable $exception): void
  50. {
  51. // 使用内置的方式记录异常日志
  52. parent::report($exception);
  53. }
  54. /**
  55. * Render an exception into an HTTP response.
  56. *
  57. * @access public
  58. * @param \think\Request $request
  59. * @param Throwable $e
  60. * @return Response
  61. */
  62. public function render($request, Throwable $e): Response
  63. {
  64. // 添加自定义异常处理机制
  65. $massageData = Env::get('app_debug', false) ? [
  66. 'file' => $e->getFile(),
  67. 'line' => $e->getLine(),
  68. 'trace' => $e->getTrace(),
  69. 'previous' => $e->getPrevious(),
  70. ] : [];
  71. if ($e instanceof DbException) {
  72. return app('json')->fail($e->getMessage(), $massageData);
  73. } elseif ($e instanceof AuthException ||
  74. $e instanceof ValidateException ||
  75. $e instanceof ApiException ||
  76. $e instanceof PayException ||
  77. $e instanceof TemplateException ||
  78. $e instanceof UploadException ||
  79. $e instanceof AdminException ||
  80. $e instanceof WechatException
  81. ) {
  82. return app('json')->make($e->getCode() ?: 400, $e->getMessage(), $massageData);
  83. } else {
  84. return app('json')->code(500)->make(400, $e->getMessage(), $massageData);
  85. }
  86. }
  87. }