业务逻辑异常类

业务逻辑异常类

Aotu Guai Sep 8, 2026
业务逻辑异常类

业务逻辑异常类

<?php

namespace App\Exceptions;

use Exception;

class BusinessException extends Exception
{
   protected $data;

   public function __construct ( $message, $code = 0, $data = [], Exception $previous = null )
  {
       $this->data = $data;
       parent::__construct( $message, $code, $previous );
  }

   // 获取额外数据
   public function getData ()
  {
       return $this->data;
  }

   // 转换为 JSON 格式
   public function toJson ()
  {
       $response = [
           'code'    => $this->getCode(),
           'message' => $this->getMessage(),
           'data'    => $this->getData(),
      ];

       if ( $this->getPrevious() ) {
           $response['previous'] = $this->getPrevious()->getMessage();
      }

       return toolJsonEncode( $response );
  }

   // 直接输出 JSON 错误
   public function renderJson ()
  {
       header( 'Content-Type: application/json' );
       http_response_code( $this->getCode() ?: 500 );
       echo $this->toJson();
       exit;
  }
}

/**
 * @param string $message
 * @param int $code
 * @return array
 */
function error ( $message = '操作失败~', $code = 500 )
{
   try {
       throw new BusinessException( $message, $code );
  } catch ( BusinessException $e ) {
       return $e->renderJson();
  }
}

/**
 * @param array $data
 * @param string $message
 * @return array
 */
function success ( $data = [], $message = '操作成功~' )
{
   try {
       throw new BusinessException( $message, 200, $data );
  } catch ( BusinessException $e ) {
       return $e->renderJson();
  }
}

Category: PHP
Share with others