Is it possible to override default error handler of CodeIgniter framework to output it as json?

16,164

Solution 1

Well maybe this solution isn't entirely useful if you are looking to return complex error objects like arrays (although you could, but you'd have to parse json on the client) but here we go:

Just use HTTP

Why? Well, you can pass a second parameter to it, which happens to be the HTTP response code, which happens to be cool, cause it allows you to make your application HTTP-aware and that works amazingly good with client-side ajax requests.

What you want to do is first define what kind of errors can happen on the backend, there is a list of HTTP error codes here.

HTTP error codes

Most likely you'll use the error codes in the 200, 400 and 500 ranges. Actually when you hit a server on your web browser it would normally receive a 200 http response code which mean everything went fine.

Have you seen those "Internal server eror" messages? Well they are 500 http response codes. And that means exactly that, it was an error from the server. Which one? It depends how you categorize them, there's a set of errors on the 500 range, but if you don't want to hassle with that just use a 500 generic error code response.

The other range is 400. Those are usually error from users, for example if you go to a url inside a server and it does not exist you'd get the famous 404 not found, 400 is a generic error code meaning that the client (in this case, the browser) requested something but the request was invalid, in the case of a 404 specifically, that the resource you requested was not found, it is a client error because you are supposed to know which resources are available on the server.

How to do it in codeigniter

It is extremely simple actually. If you see the show_error() reference on the documentation it states that the method receives a first parameter as the error message, and a second, optional, that receives an error code. Which error code? The HTTP codes we talked about before, so:

show_error('Howdy, this is my debug message', 500);

Would send a 500 HTTP response code to the client, including your message.

How to catch in AJAX

Considering you are using jQuery this is what you would normally do:

$.ajax({
    type: 'POST',
    url : example.com/resource,
    data: $("#some-form").serialize(),
    dataType: 'json',
    success : function(data, textStatus, req) {
        //do something with data which is a json object returned from PHP
    },
    error: function(req, textStatus, errorThrown) {
        //this is going to happen when you send something different from a 200 OK HTTP
        alert('Ooops, something happened: ' + textStatus + ' ' +errorThrown);
    }
});

If you were using any other toolkit or even the DOM object directly you can still catch those since they are simply XMLHttpRequest objects and chances are your toolkit has a callback for either an HTTP error response or a success response.

Why would I care?

Because it follows standards, its easier to debug, you delegate that work to the show_error() helper which is there for a reason and most importantly because all the cool kids are using it.

Cool, but wait, I don't see my custom error message nowhere!

That is right, because when you catch the request in the error callback of jquery what you get is the generic error description and the code like "Internal server error" and 500 respectively, however, you still got a pretty html response with your custom debug message, to see it just use some sort of developer tool for firefox or chrome. For example, if you use google chrome you can open the developer tools:

Go to network tab and you'll see the HTTP request, click on its name

Network details

You'll see the details and your custom error message with the usual CI template, this was the html returned with your message inside the request

Request response

Finally if you want to dig further and debug exactly what was sent from php/web server to the client go to the headers option

Headers info

Disclaimer: Screenshots were not taken from a production server :)

Solution 2

Found answer googling a bit more... on "Oliver Smith" blog.

i add this function into CI core functions by extending CI_Exceptions with this:

function show_error($heading, $message, $template = 'error_general', $status_code = 500)
{
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-type: application/json');
    header("HTTP/1.1 500 Internal Server Error");

    echo json_encode(
        array(
            'status' => FALSE,
            'error' => 'Internal Server Error',
            'message' => $message
        )
    );

    exit;
}

All credits to "Oliver Smith".

Share:
16,164
Dreanmer
Author by

Dreanmer

More than 12 years working in the software development area, I am a fullstack developer with expertise in engineering and architecture for scalable systems in PHP.

Updated on June 04, 2022

Comments

  • Dreanmer
    Dreanmer about 2 years

    The show_error function of CodeIgniter handle the errors, there is some way to override it to output their info as a json object?

    • ARIF MAHMUD RANA
      ARIF MAHMUD RANA almost 11 years
      Are you using any library like jquery, mootools ?
    • Dreanmer
      Dreanmer almost 11 years
      Yes,i use a form with ajax (jquery), and when the response is an error, they popup me the error details. If you need more details i can explain...
  • kbtz
    kbtz over 9 years
    Nice answer man! Sad it doesn't got much attention...
  • Pixelomo
    Pixelomo over 7 years
    I agree this is a great answer
  • Dreanmer
    Dreanmer over 6 years
    @gustavo perhaps I've used my own answer (on that time) i assume (now) that your answer was far better