关于 dingoapi 的 ValidationHttpException

我在 request 中使用 rules ,如果没有通过验证,状态码(status_code)会被自动设置为自动设置为 422,但是前端对于 422 的处理,会认为是网络错误,不会解析json。前端要求在状态码为200时返回验证错误的消息提示。

关于 dingoapi 的 ValidationHttpException

请问,我应该怎么把 ValidationHttpException 抛出的响应的状态码改为200呢?
除了不使用laravel的自动验证,自已手动校验外,还有更好的办法做这件事么?

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
liyu001989
5年前 评论
讨论数量: 8
liyu001989

restful 判断状态码是个非常正常的事情,前端一定是可以判断的,只是他不想而已。

你全部返回200 就需要在 body 中增加字段,说明当前的响应状态,如果你一定要这么干 参考 问答:返回的数据想要包裹多的 code 和 message 两项,该怎么处理?

5年前 评论

@liyu001989 谢谢了。我使用了您说的方法,body里面的状态码是可以自由设置了,可是真正的http的响应码依然是422的,前端直接认为是网络错误,不去解析json。怎么把http的响应码改为200呢?

5年前 评论
liyu001989
5年前 评论

已经在register里面强制把 status_code 设为了 200。
但是我还想要获取原来的状态码,然后通过它判断响应是否异常

public function register()
    {
        \API::error(function (\Dingo\Api\Exception\ResourceException $exception) {
            $status = $exception->getStatusCode();
            $message = !empty($exception->getErrors()->first())?$exception->getErrors()->first():'success';
            abort_if(in_array($status, config('api.except_status_codes')), 200, $message, ['except_status_code'=>$status]);
        });

    }

我在header头里面传入原来的状态码,请问在怎么获取这个传值呢?我想在 encode() 里面 自定义format的时候新加一个code标识出响应是否异常。这种方法好像不可行,因为我没有想到获得header头中except_status_code值的方法。请问我这个需求该怎么实现呢?

<?php

namespace App\Http\Response\Api\Format;

use Dingo\Api\Http\Response\Format\Json;

class SelfJson extends Json
{
    /**
     * Encode the content to its JSON representation.
     *
     * @param mixed $content
     *
     * @return string
     */
    protected function encode($content)
    {
        $jsonEncodeOptions = [];

        // Here is a place, where any available JSON encoding options, that
        // deal with users' requirements to JSON response formatting and
        // structure, can be conveniently applied to tweak the output.

        if ($this->isJsonPrettyPrintEnabled()) {
            $jsonEncodeOptions[] = JSON_PRETTY_PRINT;
        }

        // 通过 except_status_code 设定 code  值
        if(判断逻辑){
            $content['code'] = '自定义code';
        }

        $encodedString = $this->performJsonEncoding($content, $jsonEncodeOptions);

        if ($this->isCustomIndentStyleRequired()) {
            $encodedString = $this->indentPrettyPrintedJson(
                $encodedString,
                $this->options['indent_style']
            );
        }

        return $encodedString;
    }
}
5年前 评论

@liyu001989 问题得到解决,我把需要传递的数据放在了数组里面,进行 json_encode 后赋值给 $message 就好了

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!