通过 jquery/ajax 和 json 抛出 php 异常的干净方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12693423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:03:01  来源:igfitidea点击:

Clean way to throw php exception through jquery/ajax and json

phpjquery

提问by madphp

Is there a clean, easy way to throw php exceptions through a json response jquery/ajax call.

是否有一种干净、简单的方法可以通过 json 响应 jquery/ajax 调用抛出 php 异常。

回答by Ja?ck

You could do something like this in PHP (assuming this gets called via AJAX):

你可以在 PHP 中做这样的事情(假设这是通过 AJAX 调用的):

<?php

try {
    if (some_bad_condition) {
        throw new Exception('Test error', 123);
    }
    echo json_encode(array(
        'result' => 'vanilla!',
    ));
} catch (Exception $e) {
    echo json_encode(array(
        'error' => array(
            'msg' => $e->getMessage(),
            'code' => $e->getCode(),
        ),
    ));
}

In JavaScript:

在 JavaScript 中:

$.ajax({
    // ...
    success: function(data) {
        if (data.error) {
            // handle the error
            throw data.error.msg;
        }
        alert(data.result);
    }
});

You can also trigger the error:handler of $.ajax() by returning a 400 (for example) header:

您还可以error:通过返回 400(例如)标头来触发$.ajax()的处理程序:

header('HTTP/1.0 400 Bad error');

Or use Status:if you're on FastCGI. Note that the error:handler doesn't receive the error details; to accomplish that you have to override how $.ajax()works :)

或者,Status:如果您使用的是 FastCGI,请使用。请注意,error:处理程序不会收到错误详细信息;要实现这一点,您必须覆盖$.ajax()工作方式:)

回答by Martin Bean

Facebook do something in their PHP SDK where they throw an exception if a HTTP request failed for whatever reason. You could take this approach, and just return the error and exception details if an exception is thrown:

Facebook 在他们的 PHP SDK 中做了一些事情,如果 HTTP 请求因任何原因失败,他们会抛出异常。您可以采用这种方法,如果抛出异常,只需返回错误和异常详细信息:

<?php

header('Content-Type: application/json');

try {
    // something; result successful
    echo json_encode(array(
        'results' => $results
    ));
}
catch (Exception $e) {
    echo json_encode(array(
        'error' => array(
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        )
    ));
}

You can then just listen for the errorkey in your AJAX calls in JavaScript:

然后,您可以error在 JavaScript 中监听AJAX 调用中的键:

<script>
    $.getJSON('http://example.com/some_endpoint.php', function(response) {
        if (response.error) {
            // an error occurred
        }
        else {
            $.each(response.results, function(i, result) {
                // do something with each result
            });
        }
    });
</script>

回答by MazarD

If all the errors should be treated in the same way (showing a dialog for example). You can do it this way:

如果所有错误都应该以相同的方式处理(例如显示一个对话框)。你可以这样做:

PHP End:

PHP端:

public function throwJsonException($msg) {
    echo json_encode(array('error'=> true, 'msg' => $msg));
}

throwJsonException('login invalid!');

jQuery End:

jQuery 结束:

$(document).ajaxSuccess(function(evt, request, settings){
    var data=request.responseText;
    if (data.length>0) {
        var resp=$.parseJSON(data);
        if (resp.error)
        {
            showDialog(resp.msg);
            return;
        }                   
    }    
});

回答by Pere

As a complement to the previous answers, instead of repeating the same code for json encoding in all your exceptions, you could set an exception handler to be used only in the needed scripts. For instance:

作为对先前答案的补充,您可以设置一个仅在所需脚本中使用的异常处理程序,而不是在所有异常中重复相同的 json 编码代码。例如:

function ajaxExceptionHandler($e) {
    echo json_encode(array(
        'error' => array(
        'code' => $e->getCode(),
        'msg' => $e->getMessage())
    ));
}

Then, in your ajax handler,

然后,在您的 ajax 处理程序中,

set_exception_handler('ajaxExceptionHandler');

回答by Raito Akehanareru

I use this approach to convert Exceptions to JSON:

我使用这种方法将异常转换为 JSON:

<?php

namespace MyApp\Utility;

use Throwable;

trait JsonExceptionTrait
{    
    public function jsonException(Throwable $exception)
    {
        return json_encode([
            'message' => $exception->getMessage(),
            'code' => $exception->getCode(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => $exception->getTrace()
        ]);
    }
}

then, simply in my controllers:

然后,只需在我的控制器中:

<?php

namespace MyApp\Controller;

use MyApp\Utility\JsonExceptionTrait;

class UserController extends AbstractController
{
    use JsonExceptionTrait;

     /**
     * @param int $userId
     * @return JsonResponse
     */
    public function getAction(int $userId): JsonResponse
    {
        try {
            $user = $this->userService->getUser($userId);
            return new Response($user);
        } catch (EntityNotFoundException $exception) {
            return new Response(
                $this->jsonException($exception),
                JsonResponse::HTTP_NOT_FOUND
            );
        }
    }