我应该如何抛出这个PHP异常,以便返回一个数组?

时间:2018-03-16 05:15:43

标签: php symfony

情况如下:

$errors = $this->validator->validate($request);

if (\count($errors) > 0) {
    $errorBag = ErrorMessageHelper::generateErrorMessage($errors);

    throw new CustomException(json_encode($errorBag), Response::HTTP_INTERNAL_SERVER_ERROR);
    }

在这里,$errorBag返回一个数组。

当我抛出此异常时:我的回复看起来像这样:

"error":{"code":500,"message":"{\"postalCode\":\"This value should have exactly 7 characters.\"}"}

注意上面的消息是json编码的。

有没有人知道如何正确抛出它(消息应该是一个合适的json对象)

我试图覆盖CustomException,但它不起作用,它返回一个空响应。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以轻松整合此课程吗? `

class JsonHandler {

protected static $_messages = array(
    JSON_ERROR_NONE => 'No error has occurred',
    JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
    JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
    JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
    JSON_ERROR_SYNTAX => 'Syntax error',
    JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);

public static function encode($value, $options = 0) {
    $result = json_encode($value, $options);

    if($result)  {
        return $result;
    }

    throw new RuntimeException(static::$_messages[json_last_error()]);
}

public static function decode($json, $assoc = false) {
    $result = json_decode($json, $assoc);

    if($result) {
        return $result;
    }

    throw new RuntimeException(static::$_messages[json_last_error()]);
}

}
`