Handler.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Exceptions;
  3. use App\Http\Controllers\Controller;
  4. use App\Services\LogService;
  5. use Exception;
  6. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  7. use Illuminate\Http\Exceptions\HttpResponseException;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Http\Response;
  10. use Symfony\Component\HttpKernel\Exception\HttpException;
  11. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  12. use Throwable;
  13. class Handler extends ExceptionHandler
  14. {
  15. /**
  16. * A list of the exception types that are not reported.
  17. *
  18. * @var array
  19. */
  20. protected $dontReport = [
  21. //
  22. ];
  23. /**
  24. * A list of the inputs that are never flashed for validation exceptions.
  25. *
  26. * @var array
  27. */
  28. protected $dontFlash = [
  29. 'password',
  30. 'password_confirmation',
  31. ];
  32. /**
  33. * Report or log an exception.
  34. *
  35. * @param Throwable $exception
  36. * @return void
  37. * @throws Exception
  38. */
  39. public function report(Throwable $exception)
  40. {
  41. parent::report($exception);
  42. }
  43. /**
  44. * Render an exception into an HTTP response.
  45. *
  46. * @param Request $request
  47. * @param Throwable $exception
  48. * @return \Symfony\Component\HttpFoundation\Response
  49. * @throws Throwable
  50. */
  51. public function render($request, Throwable $exception)
  52. {
  53. try{
  54. if(strpos($exception->getMessage(),'This action is unauthorized')!==false){
  55. return response()->view('exception.unauthorized');
  56. }
  57. $errMsg=(function()use($exception){
  58. return $errMsg=
  59. '异常: '
  60. .' code:'.$exception->getStatusCode()??''
  61. .' message:'.$exception->getMessage()??''
  62. .' trace:'.$exception->getTraceAsString()??'';
  63. })();
  64. if (method_exists($exception,'getStatusCode')) {
  65. $code = $exception->getStatusCode();
  66. switch ($code){
  67. case 419: $view='exception.login';break;
  68. case 404:$view='exception.404';break;
  69. default: $view='exception.default';break;
  70. }
  71. return response()->view($view,[
  72. 'code'=> $code,
  73. 'message'=>$exception->getMessage(),
  74. ]);
  75. }
  76. }catch (\Exception $e){}finally{
  77. LogService::log(__METHOD__,__FUNCTION__,
  78. $errMsg??''
  79. .'请求:'.json_encode($request->all())
  80. .'调用堆栈:'.json_encode(array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),0,4))
  81. );
  82. }
  83. return parent::render($request, $exception);
  84. }
  85. }