0

Разрабатываю api, пользуюсь встроенной валидацией Request, В случае успешной валидации возвращается json(все хорошо), в случае не успешной валидации возвращается html страница. в хедере передаю application/json. Как вернуть ошибку в json формате? Может кто уже сталкивался? В доках тупо не могу найти, с аджаксом все окей, ошибка возвращается в json с статусом(422)(вроде), а вот обычный запрос через curl как то не выходит сделать

2
  • А как вы возвращаете ошибку? В каком виде возвращается ошибка — просто надпись о 422 ошибке или ларавелевская заглушка / stack? 12 сен 2018 в 9:13
  • Ларавельская заглушка 12 сен 2018 в 10:45

3 ответа 3

1

Все Exceptions обрабатываются в Exceptions/Handler.php там и нужно проверять! Вот мой обработчик для API:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Exception $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    return $this->checkValidationException($request, $exception);
}

/**
 * Check for validation exception.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Exception $e
 *
 * @return mixed
 */
private function checkValidationException($request, $e)
{
    if ($e instanceof ValidationException && $request->is(RouteServiceProvider::SSO_PATTERN)) {
        return response()->json([
            'code' => $e->status,
            'message' => $e->getMessage(),
            'errors' => $e->errors()
        ], $e->status);
    } elseif ($e instanceof TokenExpiredException) {
        return response()->json(['message' => 'Token is Expired'], Response::HTTP_UNAUTHORIZED);
    } elseif ($e instanceof TokenInvalidException) {
        return response()->json(['message' => 'Token is Invalid'], Response::HTTP_UNAUTHORIZED);
    } elseif ($e instanceof JWTException) {
        return response()->json(['message' => 'Unauthenticated.'], Response::HTTP_UNAUTHORIZED);
    }

    return return parent::render($request, $e);
}
0

Вы используете заголовок Accept: application/json?

Попробуйте создать метод wantJson который возвращает true:

namespace App\Http\Requests;

class ApiRequest extends Request
{
    public function wantsJson()
    {
        return true;
    }
}
1
  • Не сработало, при наследовании, методы all() и post() ничего не возвращают 12 сен 2018 в 11:33
-1

Не знаю на сколько это правильное решение(догадываюсь, что можно сделать более изящно) но пока дошел до такого решения: Сделал обертку Request

namespace App\Http\Requests\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ApiRequest

{

    protected $request = null;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function __call($name, $arguments)
    {
        if (method_exists($this->request, $name)) {
            return call_user_func_array([$this->request, $name], $arguments);
        }
    }

    public function __get($name)
    {
        if (property_exists($this->request, $name)) {
            return $this->request->{$name};
        }
    }

    public function __set($name, $value)
    {
        if (property_exists($this->request, $name)) {
            return $this->request->{$name} = $value;
        }
    }

    public function validateWithErrors()
    {
        $output = [];
        $validator = Validator::make($this->request->all(), $this->rules(), $this->messages());
        if ($validator->fails()) {
            $output = $validator->messages();
        }

        return $output;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required',
            'http_server' => 'required|string',
            'oc_version' => 'required|min:7|max:14',
            'extension_code' => 'required|string'
        ];
    }

    public function messages()
    {
        return [
            'email.required' => 'Custom error',
            'http_server.required' => 'Custom server'
        ];
    }
}

В клиентском коде:

$output['errors'] = $request->validateWithErrors();

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.