Handler.php 2.3 KB

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