ExceptionHandle.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace app;
  3. use think\db\exception\DataNotFoundException;
  4. use think\db\exception\ModelNotFoundException;
  5. use think\exception\Handle;
  6. use think\exception\HttpException;
  7. use think\exception\HttpResponseException;
  8. use think\exception\ValidateException;
  9. use think\exception\ErrorException;
  10. use think\exception\ClassNotFoundException;
  11. use think\exception\FuncNotFoundException;
  12. use think\exception\InvalidArgumentException;
  13. use think\exception\RouteNotFoundException;
  14. use think\Response;
  15. use Throwable;
  16. /**
  17. * 应用异常处理类
  18. */
  19. class ExceptionHandle extends Handle
  20. {
  21. /**
  22. * 不需要记录信息(日志)的异常类列表
  23. * @var array
  24. */
  25. protected $ignoreReport = [
  26. HttpException::class,
  27. HttpResponseException::class,
  28. ModelNotFoundException::class,
  29. DataNotFoundException::class,
  30. ValidateException::class,
  31. ];
  32. /**
  33. * 记录异常信息(包括日志或者其它方式记录)
  34. *
  35. * @access public
  36. * @param Throwable $exception
  37. * @return void
  38. */
  39. public function report(Throwable $exception): void
  40. {
  41. // 使用内置的方式记录异常日志
  42. parent::report($exception);
  43. }
  44. /**
  45. * Render an exception into an HTTP response.
  46. *
  47. * @access public
  48. * @param \think\Request $request
  49. * @param Throwable $e
  50. * @return Response
  51. */
  52. public function render($request, Throwable $e): Response
  53. {
  54. // 需要写日志的错误
  55. if($e instanceof Exception || $e instanceof HttpException || $e instanceof ErrorException || $e instanceof ClassNotFoundException || $e instanceof FuncNotFoundException || $e instanceof InvalidArgumentException){
  56. // 把系统错误写入开发者日志,方便API、回调等场景跟踪异常错误
  57. $ErrLogMSG = "错误文件".$e->getFile().'/错误行:'.$e->getLine().'/错误内容:'.$e->getMessage();
  58. WLog('FastPHP_SysError',$ErrLogMSG);
  59. return $this->json('操作异常',2,$e->getFile().':'.$e->getLine().$e->getMessage(),$e->getTrace());
  60. }
  61. if(!empty($e->getMessage())){
  62. return $this->json($e->getMessage(),2,$e->getFile().':'.$e->getLine().$e->getMessage(),$e->getTrace());
  63. }
  64. // 其他错误交给系统处理
  65. if(false===strpos($e->getMessage(),'登录失效')){
  66. return parent::render($request, $e);
  67. }
  68. }
  69. private function json(string $msg,int $code,string $info,array $extend=[])
  70. {
  71. $debug = env('APP_DEBUG',false);
  72. if($debug){
  73. return json(compact('code','msg','info','extend'));
  74. }else{
  75. return json(compact('code','msg'));
  76. }
  77. }
  78. }