namespace App\Http\Middleware;
use Closure;
class JsonApplication
{
public function handle($request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
}
namespace App\Enums;
abstract class Enum
{
public static function __callStatic($name, $arguments)
{
return new static(constant('static::' . $name));
}
}
错误码 这里因为用到了魔术方法,所以要在注视中标注
namespace App\Enums;
/**
* @method static CodeEnum OK
* @method static CodeEnum ERROR
*/
class CodeEnum extends Enum
{
public const OK = ['0', 'ok'];
public const ERROR = ['99999', 'fail'];
private $code;
private $msg;
public function __construct($param)
{
$this->code = reset($param);
$this->msg = end($param);
}
public function getCode()
{
return $this->code;
}
public function getMsg()
{
return $this->msg;
}
}
自定义异常类
namespace App\Exceptions;
use App\Enums\CodeEnum;
use Exception;
use Illuminate\Support\Facades\Log;
class ApiException extends Exception
{
public function __construct(CodeEnum $enum)
{
parent::__construct($enum->getMsg(), $enum->getCode());
}
public function report()
{
Log::error("ApiException {$this->getFile()}({$this->getLine()}): code({$this->getCode()}) msg({$this->getMessage()})");
}
public function render($request)
{
return response([
'code' => $this->getCode(),
'msg' => $this->getMessage(),
'data' => ''
]);
}
}
调用
throw new ApiException(new CodeEnum(CodeEnum::ERROR)); // 这样调总感觉不太好看
throw new ApiException(CodeEnum::OK()); // 这样调用和java的调用方式就很像了