Welcome Guest, Not a member yet? Register   Sign In
Not sure to migrate to CI4
#14

(This post was last modified: 05-18-2020, 01:16 PM by bivanbi.)

I found throwing a generic exception made my life harder in the long run. I definitely want to differentiate, for instance, a real generic error like backend DB unreachable vs. user is not logged in / not having the required rights to perform action etc. When I catch the exception, I find it much cleaner with different Exception classes:

Code:
class MyController extends BaseController {
    public function main()
    {
        try {
            doSomething();
        } catch (\Exception $e) {
            myCustomErrorHandling($e);
        }
    }

    private function doSomething()
    {
        // require user to be logged in and have permission to access this function
        requireRole(USER_ROLE_ADMIN);
        // do the actual work
    }
}


class BaseController {
    protected function myCustomErrorHandling($e)
    {
        if ($e instanceof UserNotLoggedInException) {
            // redirect to login page
        } else if ($e instanceof AccessDeniedException {
            // let the user know he/she has no access to the given function
        } else {
            // redirect to a generic error page
        }
    }

    protected function requireRole(string $role)
    {
        if (! isLoggedIn()) {
           throw new UserNotLoggedInException("Must be logged in");
        }

        if (! hasRole($role)) {
           throw new AccessDeniedException("No permission to access");
        }
    }
}
Reply


Messages In This Thread
Not sure to migrate to CI4 - by imabot - 05-12-2020, 08:11 AM
RE: Not sure to migrate to CI4 - by bivanbi - 05-12-2020, 09:21 PM
RE: Not sure to migrate to CI4 - by imabot - 05-13-2020, 01:52 AM
RE: Not sure to migrate to CI4 - by John_Betong - 05-13-2020, 02:27 AM
RE: Not sure to migrate to CI4 - by imabot - 05-13-2020, 04:12 AM
RE: Not sure to migrate to CI4 - by John_Betong - 05-13-2020, 02:52 PM
RE: Not sure to migrate to CI4 - by admin0 - 05-14-2020, 08:07 AM
RE: Not sure to migrate to CI4 - by imabot - 05-14-2020, 08:13 AM
RE: Not sure to migrate to CI4 - by includebeer - 05-15-2020, 03:05 PM
RE: Not sure to migrate to CI4 - by albertleao - 05-14-2020, 09:37 AM
RE: Not sure to migrate to CI4 - by imabot - 05-18-2020, 02:09 AM
RE: Not sure to migrate to CI4 - by includebeer - 05-18-2020, 04:49 AM
RE: Not sure to migrate to CI4 - by bivanbi - 05-18-2020, 05:19 AM
RE: Not sure to migrate to CI4 - by 68thorby68 - 06-10-2020, 01:25 PM
RE: Not sure to migrate to CI4 - by jreklund - 06-13-2020, 08:13 AM



Theme © iAndrew 2016 - Forum software by © MyBB