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')
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
How to display notice or success message during the import by the Convert Adapter ?
I can only display error by
Mage::throwException($message)
.
Class responsible for this is Mage_Adminhtml_Block_System_Convert_Profile_Run.
Magento actually have some kind a session message stack. (Something quite similar to the message bags you can find, for example on Symphony).
Those are quite easy to use, just get the session associated to the area you are in and use on of the functions addError, addWarning, addNotice or addSuccess.
Since you are on the data flow module, the session you are looking to is dataflow/session. Take care to get this model via a singleton otherwise, you will end up with odd multiple sessions.
Mage::getSingleton('dataflow/session')->addSuccess($this->__('This will add a success message'));
The other are :
Mage::getSingleton('dataflow/session')->addNotice($this->__('This a notice'));
Mage::getSingleton('dataflow/session')->addWarning($this->__('That a warning'));
Mage::getSingleton('dataflow/session')->addError($this->__('And finally an error'));
And the reason you actually get an error message when you throw an exception, is because somewhere on Magento core, there is a
try {
// the code or class instantiation on which you throw your exception happens here
} catch (Mage_Core_Exception $e) {
Mage::getSingleton('dataflow/session')->addError($e->getMessage());
}
I'm trying to format user input with the following code:
$userInput="blalalbla";//assume the user is inputing wrong data, they are supposed to input it like "12:30"
try{
$timeStr=explode(":",$userInput);
$time=(new Datetime())->setTime($timeStr[0],$timeStr[1]);
}catch(ErrorException $e){
}
However, if the input is not in the right format, laravel4 will always fire an ErrorException and I have no way of catching it. Since the user input can be wrong in different ways, I thought this was the most elegant way of handling validation. As ridiculous as it sounds like, ErrorExceptions seem to be un-catchable. What other options do I have?
The actual error received in your code is a PHP Notice. You can't catch it because it isn't an exception at that point in time. Laravel defines the class Illuminate\Exception\Handler and uses PHP's set_error_handler() to turn PHP errors into ErrorExceptions.
To use a try/catch block in your controller, you'll have to throw the exception yourself in that area (or use code that throws exceptions). However, as most have commented, you should be doing appropriate input checking and sanitation prior to actually using the input in any code. Whether or not poor input throws exceptions is totally up to you.
set a global error handler
set_exception_handler (handler);
function handler($e) {
if($e instanceof TheExceptionYouWantToHandle) {
//then handle it
}
}
During the process of my PHP learning I have been trying to read up on the best practices for error reporting and handling, but statements vary person to person and I have struggled to come up with a clear concise way of handling errors in my applications. I use exceptions on things that could go wrong, but for the most part it is hard for me to understand whether an exception should kill the application and display an error page or just be caught and silently dealt with.
Something that seems to elude me is, is there such thing as too much reporting? Every single time you call a function something could go horribly wrong meaning that if you were to confirm every single function call you would have to fill pages with if statements and work out what effect one failure may have on the rest. Is there a concise document or idea for error reporting that could clear this up for me? Are there best practices? What are the best examples of good error handling?
Currently I do the following:
Add important event results to an array to be logged and emailed to me if a fatal error was to occur
Display abstract/generic errors for fatal errors.
Use exceptions for cases that are likely to fail
Turn on error reporting in a development environment and off for live environment
Validate all user input data
Sanitizing invalid user input
Display concise, informative error messages to users without providing a platform for exploitation.
Exceptions are the only thing that you haven't understood IMHO: exceptions are meant to be out of your control, are meant to be caught be dealt with from outside the scope they are thrown in. The try block has a specific limit: it should contain related actions. For example take a database try catch block:
$array = array();
try {
// connect throws exception on fail
// query throws exception on fail
// fetch results into $array
} catch (...) {
$array[0]['default'] = 'me';
$array[0]['default2'] = ...;
...
}
as you can see I put every database related function inside the try block. If the connection fails the query and the fetching is not performed because they would have no sense without a connection. If the querying fails the fetching is skipped because there would be no sense in fetching no results. And if anything goes wrong, I have an empty $array to deal with: so I can, for example, populate it with default data.
Using exceptions like:
$array = array();
try {
if (!file_exists('file.php')) throw new Exception('file does not exists');
include('file.php');
} catch (Exception $e) {
trigger_error($e->getMessage());
}
makes no sense. It just a longer version of:
if (!file_exists('file.php')) trigger_error('file does not exists');
include('file.php');
I am using the Zend MVC framework along with an ORM layer generated with Propel, and I'm trying to figure out the best way to catch exceptions from a Propel object's save() function, and throw them to the Zend Form as errors.
Not all of the exceptions that come out of the Propel object have a way to identify which field caused the error, so I'm wondering if there is a way to add generic error messages to the entire form, rather than being forced to attach each error message to a particular form element.
For example, I have a save() call wrapped in a try/catch block, and I can add the exception->getMessage() to a form element's errors:
try {
$obj->save();
echo 'object saved successfully';
} catch (Exception $e) {
$form->name->addErrorMessage($e->getCode()." - ".$e->getMessage());
$form->name->markAsError();
$form->populate($formData);
}
but I would like to be able to do something like this:
try {
$obj->save();
echo 'object saved successfully';
} catch (Exception $e) {
$form->addErrorMessage($e->getCode()." - ".$e->getMessage());
$form->markAsError();
$form->populate($formData);
}
I hope that makes sense, thanks for the help,
Dave
Are you thinking about the errors from the database, or from the Propel validation layer (which isn't developed that much, and not used by default in the save() step)?
If you want to use the database errors, keep in mind that they will only return the first error (so the user has to submit four times if they entered three errors). Also, getting the field name out of the error message can be hard. Keep in mind that some keys cover multiple fields ("the combination of name and first_name must be unique").
This is why for example Symfony adds validation in the form layer. There, you can check all fields at once, and return multiple errors. But maybe you already do this, and only want this as a final check?