Search code examples
codeigniterexceptioncodeigniter-4

How to make Exception much simpler CodeIgniter4


so, I have JWT authentication API using CI4, and one of the method is filtering which is telling if you has the token for JWT or not, if the user don't have the token it will return to an exception telling that JWT authentication is failed like this :

Postman : Postman Exception

Web : Web Exception

is it possible to make it more simpler like this ?, just a response and without a trace exception like in the first image

Here is the jwt_helper.php :

<?php

use App\Models\AuthModel;
use Firebase\JWT\JWT;

function getJWT($headerAuth)
{
    if (is_null($headerAuth)) {
        throw new Exception("JWT Authentication failed");
    }
    return explode(" ", $headerAuth)[1];
}

function validateJWT($encodedToken)
{
    $key = getenv('JWT_SECRET_KEY');
    $decodedToken = JWT::decode($encodedToken, $key, ['HS256']);
    $authModel = new AuthModel();
    // * xxxx.xxxx.xxxx
    $authModel->getEmail($decodedToken->email);
}
function createJWT($email)
{
    $requestTime = time();
    $tokenTime = getenv('JWT_TOKEN_TIME');
    $tokenExpireTime = $requestTime + $tokenTime;
    $payload = [
        'email' => $email,
        'iat' => $requestTime,
        'exp' => $tokenExpireTime
    ];
    $jwt = JWT::encode($payload, getenv('JWT_SECRET_KEY'), 'HS256');
    return $jwt;
}

Solution

  • This full stack is displayed only in DEVELOPMENT.

    Edit your .ENV file accordingly.

    CI_ENVIRONMENT = production
    

    UPDATE : More details

    So, of course, you have to write the error in a log file. This is probably already the case: you can check the CI log in the /writable/logs directory and the PHP log which is in your PHP directory (you can look for the error_log variable in your phpinfo).

    Then you should try to display a simple and understandable error to your users, typically by redirecting them to /views/errors/html/production.php but giving them a bit more detail if you want, and/or specifying a HTTP_STATUS or an EXIT CODE (CI 4.3+).

    The DEVELOPMENT mode (specified in the .env) is however not recommended because you will give too many details to the user and this can be harmful (display of connections, directories, etc.).

    I recommend you to read this page : https://codeigniter.com/user_guide/general/errors.html#