Handler.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Exceptions;
  3. use App\Exceptions\Admin\AuthException;
  4. use App\Exceptions\Api\ApiException;
  5. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  6. use App\Facades\Servers\Logs\Log;
  7. use Throwable;
  8. class Handler extends ExceptionHandler
  9. {
  10. /**
  11. * 不报告的异常类型的列表
  12. *
  13. * @var array
  14. */
  15. protected $dontReport = [
  16. //
  17. ];
  18. /**
  19. * A list of the inputs that are never flashed for validation exceptions.
  20. *
  21. * @var array
  22. */
  23. protected $dontFlash = [
  24. 'current_password',
  25. 'password',
  26. 'password_confirmation',
  27. ];
  28. /**
  29. * Register the exception handling callbacks for the application.
  30. *
  31. * @return void
  32. */
  33. public function register()
  34. {
  35. $this->reportable(function (Throwable $e) {
  36. })->stop();
  37. }
  38. /**
  39. * 将异常呈现到HTTP响应中
  40. *
  41. *
  42. * @return \Illuminate\Http\JsonResponse
  43. */
  44. public function render($request, Throwable $e){
  45. // 如果不是接口,
  46. if( !$request->is('api/*') ) {
  47. // 如果是后端验证类
  48. if( $e instanceof AuthException ) return $e->jumpPage();
  49. // 如果不是验证返回,调用父级异常呈现
  50. if( !($e instanceof ApiException) ) return parent::render($request, $e);
  51. }
  52. // 如果是异常类型,获取异常的消息
  53. $msg = $e->getMessage();
  54. // 错误信息
  55. $msg = $msg ? $msg : '404';
  56. // 错误数据
  57. $data = '';
  58. // 错误码
  59. $code = 'sys_error';
  60. // http状态码
  61. $status = 200;
  62. // 日志信息
  63. $message = request()->ip().' ' .request()->method().' '. request()->getPathInfo().' '.$msg;
  64. // 如果是接口异常
  65. if( $e instanceof ApiException ){
  66. // 错误码
  67. $code = $e->getErrCode();
  68. // 错误数据
  69. $data = $e->getErrData();
  70. }else{
  71. // 拼接报错文件位置
  72. $message .= ' of file '.$e->getFile().' on line '.$e->getLine();
  73. }
  74. // 要返回的数据
  75. $data = ['code'=>($code == 'sys_error' ? 'error' : $code),'msg'=>$msg,'data'=>$data];
  76. // 记录日志
  77. Log::info($code,$message,['param'=>request()->all(),'return'=>$data,'user_agent'=>request()->header('user-agent')],['filename'=>str_ireplace('/','_',trim(request()->getPathInfo(),'/'))]);
  78. // 返回结果
  79. return response()->json($data,$status,[],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  80. }
  81. }