I am wanting to create a registration verification,
So far I have planned out, that my Users table should have a confirmation_code column, and an confirmed column. The confirmed column has a default value of 0 (boolean false).
I create the new User from registration and assign them a confirmation_code.
I then email them a link to the verify route, which expects this confirmation_code in the query string.
The method which handles the verify request will be checking to see if the query string parameter (confirmation_code) exists.
My question is :
If the confirmation_code is absent, should I use the abort(404) method? Or throw a custom exception?
public function verify($confirmation_code)
{
if ( ! $confirmation_code ) {
// abort(404)?
// or,
// throw new Exception?
}
Some feedback on when to use the abort method would be appreciated too.
It's actually your choice to choose what type of error handling and error logging you implement in your project.
As advice, I will say that using custom exceptions for missing field exceptions. is a better idea. You can read more about a 404 error in the given link:
404 error.
Also refer to laravel documentation for more details regarding error logging.
Related
I am using latest version laravel(5.6)
Now in my code whenever an exception occurs laravel treating it as a fatal error, stop executing instantly and displaying the error message in some template.
But I don't want that, I want to handle exceptions and display some custom error messages
I found some ways like
changing the APP_DEBUG value in the .env file to false. But this also displays another
page with the message "whoops!some this want wrong";
In Handler.php which is in app/Exceptions, I had put some exceptions in not report zone. But the app is still reporting them
Custom HTTP Error Pages
Laravel makes it easy to display custom error pages for various HTTP
status codes. For example, if you wish to customize the error page for
404 HTTP status codes, create a resources/views/errors/404.blade.php.
This file will be served on all 404 errors generated by your
application. The views within this directory should be named to match
the HTTP status code they correspond to. The HttpException instance
raised by the abort function will be passed to the view as an
$exception variable.
https://laravel.com/docs/5.6/errors#custom-http-error-pages
Really you want to be handling your exceptions. Wrap the code in a try catch and you can do all manner of things (e.g. email / slack / log). Once you have handled the exception you can still use custom http error pages inside the catch so the end user get's a friendly message on a nicely designed page. There is even a report helper built in to allow you to externally log and continue on processing the code.
#Devon's above answer re: Custom HTTP Error Pages gets you exactly what you want also.
Please note few important points :
The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. This class has two method report() and render(), both has their own responsibility.
The report method is used to log exceptions. By default, the report method passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish. For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof comparison operator
The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response.
As in your case you want to return custom message for exception, inside render() you may use the PHP instanceof comparison operator and return you own logic.
Example :
if($exception instanceof PostTooLargeException || $exception instanceof FileException){
return response()->json([
'error' => true,
'error_message' => "The file you are trying to upload exceeds the maximum limit. Please try to upload a smaller file."
],200);
}
Go through https://laravel.com/docs/5.6/errors for more datails
I am facing a problem with my database models in ZF2, I must have touch something in the application as I am sure it worked before.
Wondering if somebody can read out the problem by the follow error messages I've got.
If more error info is needed I can update this question with the stacks :)
Zend\ServiceManager\Exception\ServiceNotCreatedException
File:
/home/xxxxx/domains/xxxx.nl/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:909
Message:
An exception was raised while creating "Application\Model\CelebrityTable"; no instance returned
**Previous exceptions:**
Zend\Db\TableGateway\Exception\RuntimeException
File:
/home/xxxx/domains/xxxx/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php:105
Message:
This table object does not have a valid table set.
Well the exceptions says most of what you need to know.
File:
/home/xxxx/domains/xxxx/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php:105
Message:
This table object does not have a valid table set.
I went to Zend/Db/TableGateway/AbstractTableGateway.php:105 and the following piece of code is there;
if (!is_string($this->table) && !$this->table instanceof TableIdentifier && !is_array($this->table)) {
throw new Exception\RuntimeException('This table object does not have a valid table set.');
}
So your exceptions means. The $this->table is not a string, array or an instanceof Zend\Db\Sql\TableIdentifier
So you probably didn't set the table.
Now I never used the AbstractTableGateway so not sure how to use it in the right context. But I don't see a setTable, or something like a setOptions.
So unless you can show your implementation of your TableGateWay, this is as far as I know.
Note, I looked at zf2.3.3
I am stuck a bit, I have a little form and auth system - Sentry.
1) Get data from Input and validate it.
It's okay, I get it, check with rules, set messageBag
<?php
$validation->getMessageBag()->setFormat(Config::get('project/config.errors_delimiters'));
?>
Then I return page withErrors method. And prints validation errors.
2) Next step will be to login users, for example. This mean, that I need to use a Sentry manual.
But now I have a problem: how to show errors or store errors.
I have:
Error messages via validation
Error messages via Sentry
Custom Errors
Success messages
Info messages
Which the best practice to store this messages? How to send it to a view? And how to parse it in a view? Also how to set delimiters style?
Of course I can create tons of flash, session, and other types of data and then send this into a view, but I think it is ridiculous. I think there is a simple method which can help me.
Very good question. This is how I handle it.
Because validation errors uses MessageBag, what I did is
$messages = new MessageBag;
and then if you run into any error, you could do
try {
...
} catch (Exception $e) {
$messages->add("error", $e->getMessage());
}
and if you have other errors returned you can merge it
$messages->merge($other_messages)
which includes validation messages $validation->messages().
Because messagebag accepts keys, you can add other type by $messages->add('info', 'ok')
And then in your template, or controller, you can get messages of that type by
$messages->get('error')
after you checked with
$messages->has('error')
I have an object oriented app (written in an MVC framework) and often my error handling procedures are ad-hoc. Sometimes I return 0 for no error, sometimes a true for success. In general there is not a lot of consistency.
My scenario is that I have a controller calling a method from my model. If that method fails, I want it to return a human-readable reason as to why the error could not be completed. This error will be passed on to the user. For instance a userDelete() method. I just want to know whether the user was deleted, and if not, why?
My previous approach was to return true if deleted, and a string otherwise. This made if statements a little tricky because
if ($output = $this->someMethod())
will return true for a string, so that doesn't help much.
My considerations for alternatives are:
Return an array
array ('status'=>'error', 'message' => 'You did not specify an existing user')
This will be compatible with the if statement shown above (i.e. will return 'false' when an array is returned). I would return true for a successful function call.
Use PHP's Exception class and try/catch blocks
When the code falls into an error (i.e. perform a check to see whether user exists, and it turns out negative)
if ($query->count == 0) {
throw new Exception("User does not exist");
}
and then on the calling page I would write:
try {
$this->someMethod();
} catch (Exception $e) {
echo $e->getMessage() //Or some other way of handling the error
}
If I proceed with this alternative, is that "bad form" in PHP? Should Exceptions be only used for actual coding errors (i.e. division by 0) instead of for 'higher level' application error handling / user feedback?
Remember: I plan on sending these error messages back to the user at some point during execution ... should I be concerned that other Exceptions thrown by PHP itself will make their way back to the user? Should I extend the Exception class to prevent this?
Personally I use something similar to your array idea since I can return and store that status and all other pieces of useful log info if I need to. If all goes well I simply return an empty array for consistency since if(someFunct()) would be true on success (if I used true as success) or on non-empty array. This way I just equate empty array (!someFunc()) to be success.
However, feel free to look at this post which I found to be pretty good about this topic.
Today I had a nice talk chat with a friend of mine. We covered few aspects of web development.
He criticised my application errors handling approach, basically if I need to check user permission to perform an action, I do the following:
// My little function
function check_user_perms($user)
{
// #returns boolean
// checking is user is permitted to perform an action
return ($something > 1) ? TRUE : FALSE; // of course it returns true/false, not null
}
// place where I need to check user permission
// please note that following lame snippets are meant to show you my approach
if( check_user_perms($user_id) )
{
// perform the action
}
else
{
echo 'You have no permission to perform this action.';
}
He said, I should use exceptions. So I started to read and think I learned good exceptions practices.
There are only few things that needs clarification:
1. Should I use exceptions for everything in web application?
2. If so, how to show a message to user on production?
3. What approach would you suggest?
Exceptions should be used for "exceptional situations". Checking if a user has proper permissions is not an "exceptional situation". It's a very common check which should not use an exception. Returning true/false here is fine.
If on the otherhand, while checking if the user has access an "exceptional" error occurs, such as the inability to check the authentication server due to it being down, then throwing an exception would be appropriate.
Here are some more resources to check out:
When and How to Use Exceptions
PHP5 Exception Use Guide
check_user_perms should absolutely return TRUE or FALSE (not NULL!).
Exceptions are for exceptional circumstances, not general program flow control.
An example might be:
If user has permission to do this action, return TRUE
If user has no permission to do this action, return FALSE
If user doesn't exist, throw an exception (because we kind of expected the user to exist if this function was called in the first place).
You should use exceptions for exceptional, i.e., unexpected or unusual conditions. Depending on the context of the check a lack of permissions could either be exceptional or not. If, for instance, your code simply does one thing for authorized users and another for unauthorized, or more commonly simply allows additional access to authorized users (say, like showing an admin menu for administrators), then you shouldn't be using exceptions for this. If, on the other hand, an unauthorized user attempts to access a web action that requires authorization or a non-administrator attempts to access an administrator-only action, then an exception could well be an appropriate response. In this case, you should catch the exception and do the appropriate thing, say redirect to a login or error action.
As a generalization, I would say that the code that determines if a user has a specific permission shouldn't throw an exception, but rather return true or false. The code invoking that call might, depending on the context, choose to throw an exception if the permission is required and expected.