<?php
declare (strict_types=1);

namespace app\api\exception;

use think\exception\Handle;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * API异常处理类
 */
class Http extends Handle
{
    public function render($request, Throwable $e): Response
    {
        $statusCode = $this->getStatusCode($e);
        $message = $e->getMessage();

        return json([
            'code' => 0,
            'msg' => $message,
            'data' => []
        ], $statusCode);
    }

    protected function getStatusCode(Throwable $e): int
    {
        if (method_exists($e, 'getStatusCode')) {
            return $e->getStatusCode();
        }

        if ($e instanceof ValidateException) {
            return 400;
        }

        return 500;
    }
}
