Handler.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Exceptions;
  3. use Exception;
  4. use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
  5. use Illuminate\Validation\ValidationException;
  6. class Handler extends ExceptionHandler
  7. {
  8. /**
  9. * A list of the exception types that are not reported.
  10. *
  11. * @var array
  12. */
  13. protected $dontReport = [
  14. ExitOutException::class,
  15. ];
  16. /**
  17. * A list of the inputs that are never flashed for validation exceptions.
  18. *
  19. * @var array
  20. */
  21. protected $dontFlash = [
  22. 'password',
  23. 'password_confirmation',
  24. ];
  25. /**
  26. * Report or log an exception.
  27. *
  28. * @param \Exception $exception
  29. * @return void
  30. */
  31. public function report(Exception $exception)
  32. {
  33. parent::report($exception);
  34. }
  35. /**
  36. * Render an exception into an HTTP response.
  37. *
  38. * @param \Illuminate\Http\Request $request
  39. * @param \Exception $exception
  40. * @return \Illuminate\Http\JsonResponse
  41. */
  42. public function render($request, Exception $exception)
  43. {
  44. if ($exception instanceof ExitOutException){
  45. $msg = $exception->getMessage();
  46. $out = json_decode($msg, true);
  47. return out($out['data'], $out['status'], $out['message']);
  48. }
  49. //如果路由中含有“api/”,则说明是一个 api 的接口请求
  50. if ($request->is("api/v*")) {
  51. //如果错误是 ValidationException的一个实例,说明是一个验证的错误
  52. if ($exception instanceof ValidationException) {
  53. return out(null, 10000, array_values($exception->errors())[0][0]);
  54. }
  55. return out(null, 500, $exception->getMessage());
  56. }
  57. return parent::render($request, $exception);
  58. }
  59. }