ExceptionHandle.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace app;
  3. use app\index\exception\ApiException;
  4. use think\db\exception\DataNotFoundException;
  5. use think\db\exception\ModelNotFoundException;
  6. use think\exception\Handle;
  7. use think\exception\HttpException;
  8. use think\exception\HttpResponseException;
  9. use think\exception\ValidateException;
  10. use think\Response;
  11. use Throwable;
  12. /**
  13. * 应用异常处理类
  14. */
  15. class ExceptionHandle extends Handle
  16. {
  17. /**
  18. * 不需要记录信息(日志)的异常类列表
  19. * @var array
  20. */
  21. protected $ignoreReport = [
  22. HttpException::class,
  23. HttpResponseException::class,
  24. ModelNotFoundException::class,
  25. DataNotFoundException::class,
  26. ValidateException::class,
  27. ];
  28. /**
  29. * 记录异常信息(包括日志或者其它方式记录)
  30. *
  31. * @access public
  32. * @param Throwable $exception
  33. * @return void
  34. */
  35. public function report(Throwable $exception): void
  36. {
  37. // 使用内置的方式记录异常日志
  38. parent::report($exception);
  39. }
  40. /**
  41. * Render an exception into an HTTP response.
  42. *
  43. * @access public
  44. * @param \think\Request $request
  45. * @param Throwable $e
  46. * @return Response
  47. */
  48. public function render($request, Throwable $e): Response
  49. {
  50. // 添加自定义异常处理机制
  51. //apiException异常的处理
  52. if ($e instanceof ApiException) {
  53. $code = $e->getCode();
  54. $message = $e->getMessage();
  55. } else {
  56. //Todo 改成三元运算符简化代码
  57. $code = $e->getCode();
  58. if (!$code || $code < 0) $code = config('status.err_token')[0];
  59. $message = $e->getMessage();
  60. if (!$message) $message=config('status.unknow_error')[1];
  61. }
  62. return show($code, $message);
  63. // 其他错误交给系统处理
  64. //return parent::render($request, $e);
  65. }
  66. }