ApiExceptionHandle.php 1.5 KB

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