Throw exception, but json response get status SUCCESS

2.4k views Asked by At

I have this part of code in Controller, but when i make this action and IF works fine and the error message appears in console log.

But it looks like 'success' has status true. And it shouldn't

Try {
    if ($last['date']) {
        if ($last['date']->format('d-m-Y') == $par['date']) {
                throw new \Exception('error', 500);
            }
    }

    return new JsonResponse([
        'success' => true,
        'data'    => $content,
        'message' => 'success'
    ]);
} catch (\Exception $exception) {

    return new JsonResponse([
        'success' => false,
        'code'    => $exception->getCode(),
        'message' => $exception->getMessage(),
    ]);
}

JQuery

$.ajax({
    type: "POST",
    url: "/app/url",
    data: TableData,
    dataType: "json",
    success: function(response){
        console.log(response.message);
        $('#message').html('<p class="alert alert-success">' + response.message + '</p>');
    },
    error: function (response) {
        console.log(response.message);
        $('#message').html('<p class="alert alert-danger">' + response.message + '</p>');
    }
});
1

There are 1 answers

2
ishegg On BEST ANSWER

Your AJAX code is receiving the response as success every time, regardless of the JSON content, because you're always sending a 200 response (which is success). To tell AJAX to process the response as an error (and go to the error method instead of success method in your AJAX response handler), you need to send an error code in the response, i.e. 400, like this:

return new JsonResponse([
        'success' => false,
        'code'    => 400,
        'message' => $exception->getMessage(),
    ], 400);

So, if you're throwing your custom Exceptions, you need to set the code property for each according to their real HTTP meaning.

Now, the success and error handlers in AJAX have different parameters. In success, the first parameter is data, simply the data returned from the server. On the other hand, in error, the first parameter is an jqXHR object. To access the data in this object, you have a handful of different parameters, but what you need now, since you have JSON, is jqXHR.responseJSON. So, now your error message will be in response.responseJSON.message, not in response.message. See more about this here.