捕捉组件抛出的异常

  1. use Swoft\Bean\Annotation\ExceptionHandler;
  2. use Swoft\Bean\Annotation\Handler;
  3. use Swoft\Http\Message\Server\Response;
  4. use Swoft\Auth\Exception\AuthException;
  5. /**
  6. * @ExceptionHandler()
  7. */
  8. class SwoftExceptionHandler
  9. {
  10. /**
  11. * @Inject()
  12. * @var ErrorCodeHelper
  13. */
  14. protected $authHelper;
  15. /**
  16. * @Handler(AuthException::class)
  17. */
  18. public function handleAuthException(Response $response, \Throwable $t) : Response
  19. {
  20. $errorCode = $t->getCode();
  21. $statusCode = 500;
  22. $message = $t->getMessage();
  23. if ($this->authHelper->has($errorCode)) {
  24. $defaultMessage = $this->authHelper->get($errorCode);
  25. $statusCode = $defaultMessage['statusCode'];
  26. if (!$message) {
  27. $message = $defaultMessage['message'];
  28. }
  29. }
  30. $error = [
  31. 'code' => $errorCode,
  32. 'message' => $message ?: 'Unspecified error',
  33. ];
  34. return $response->withStatus($statusCode)->json($error);
  35. }
  36. }