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");
}
}
}