/    Sign up×
Community /Pin to ProfileBookmark

Throwing an exception

I’m trying to throw an exception and error out of a function.

Currently I get this error

>

Fatal error: Uncaught Exception: You don’t have permission to do this. in /home2/grettd/public_html/oop/player.php:397 Stack trace: #0 /home2/grettd/public_html/admin/playerAdd-update.php(104): Player->updateDatabase() #1 {main} thrown in /home2/grettd/public_html/oop/player.php on line 397

I was hoping for a cleaner error like here

https://www.php.net/manual/en/language.exceptions.php

here’s my code

“`
if ($Session->validateAccess(2) == false){
throw new Exception(‘You don’t have permission to do this.’);

exit();
}
“`

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@kiwisauthorFeb 16.2021 — I worked this one out. Remove the exit() script. Call an if statement no the page calling this method.

Bed time I think
Copy linkTweet thisAlerts:
@NogDogFeb 16.2021 — You probably want a try/catch block so you can handle it as desired, e.g.:
<i>
</i>try {
// assorted code, including that which calls that function/method
}
catch(Exception $e) {
error_log($e-&gt;getMessage()." in ".$e-&gt;getFile()." at line ".$e-&gt;getLine());
die("&lt;p class='error'&gt;Sorry...there was an unexpected error. It has been logged for our developers to look at.&lt;/p&gt;");
}

Now, if it might be relatively normal for the user to not have that access which is causing this particular problem, then it probably should not be handled as an exception. I.e., if you want to respond in a specific way for that condition, it's not really practical to do it via an exception, as the catch will fire on _any_ exception. In that case you might be better off just outputting the error message to the user and then exiting or redirecting -- whatever makes sense.
Copy linkTweet thisAlerts:
@NogDogFeb 16.2021 — Heh...I was typing when you replied. :)
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...