Yii2 UploadedFile saveAs() error handling - yii2

I have a controller action that accepts a file upload via ajax request and saves basic info about the file. If the save was successful, it then executes saveAs() to actually save the file to the filesystem. A little something like this:
if ($model->save()) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
Everything works great but I'd like to implement a check around the saveAs() so I can delete the just-inserted-record if the file, for some reason, can't be saved. I see that UploadedFile has a $hasError and $errors but if there is a problem saving the file code execution seems to stop at the saveAs(), not moving past it to actually let me handle the error.
Is there a way for me to catch saveAs() errors and perform some logic if there is a problem saving?
EDIT
I have tried assigning the return variable as in the following. However, this is how I first noticed that if a saveAs() error occurs, no code gets executed past the saveAs().
$saveResult = $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
// Any code down here won't be executed if (for example)
// that "uploads" directory doesn't exist and the saveAs() fails

If this code throws an exception (directory not exist, not writable, etc.), you can use a regular try - catch block to handle that:
try {
$file->saveAs(...);
} catch (\Exception $e) {
...
}
Read official PHP docs about exceptions.
Another alternative is to add checks to prevent all most common possible errors:
if (!is_dir($uploadPath)) {
...
}
if such directory not exist, etc.
To get rid of that, I'd recommend to write tests and create that folders in deploy script (if they not exist).

Related

Laravel 8.5's Validation is not working and getting an error

I am just calling an API with one array parameter with the required validation. But I am getting always an error message. The weird thing is that it has been working since I created the project but it suddenly stopped working today. I also cleared config:cache and apply the composer dumpautoload command till the issue remains the same.
first, try to dump all the input data using dd helper and see if the input format is correct
so in the first line of your function dump it like below the check the output
dd( $request );
secondly, use the validate function of $request object
so instead of calling and using Validator class,
call it on the request object at the very first line of your function
$request ->validate([
'booking_data' => 'required|array'
]);
and you don't need to manually check any validation and manually return something, it will automatically throw an error if it fails

Exception handling onException() using Apache Camel

I am trying to handle Exception in my code. Below is the code:
public void configure() throws Exception {
onException(Exception.class).process(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("handling ex");
}
}).log("Received body").handled(true).end();
from("file:src/main/resources?fileName=data.csv")
.process(new MyTransformRevised1())
.to("file:src/main/resources/?fileName=emp.xml")
.split(body().tokenizeXML("equityFeeds", null)).streaming().to("jms:queue:xml.inbound.topic");
}
Now if suppose in the line: from("file:src/main/resources?fileName=data.csv") if the file "data.csv" is not present in my resources folders then shouldn't it throw FileNotFoundException and go into the onException() handler and print "handling ex"? Also when this code runs my log statement is also not printed to the console.
Currently its not going into the onException() handler. I am failing to understand as to why? Please kindly help me solve this issue.
As #bedla already commented, you will not get a FileNotFoundException because `from("file:...") creates a file consumer that is listening continuously for new files in the directory you configure.
The filename option acts as a filter. That means your file consumer processes only files with the name data.csv.
So if you drop a file with this name, it will be consumed and moved to a subfolder (I think the default name is .camel). Then you can drop another data.csv into the folder and it will be consumed too. If you remove the filename option, it consumes every file you drop into the folder.
If you don't want to have a continuous file import from a folder, but want to import a specific file as part of your processing workflow, have a look at Camel Poll Enrich EIP. There is a simple example that imports a file.

How do I declare that a function dies so it is detected by PhpStorm?

Background
I use several helper functions to stop the program flow and return data. For example, while most pages are HTML I occasionally return JSON and call
/**
* #param array|bool $response
*
* #die
*/
function jsonResponseDie($response)
{
header('Content-Type: application/json');
echo json_encode($response);
die();
}
The Problem
However, the calling function does not detect that there is a die statement and allows code to be present after it without warning.
function recievePush()
{
// Process a push request and respond with a json array.
jsonResponseDie(array('status' => TRUE));
echo 'This will never execute but PhpStorm doesn\'t know that';
}
The Question
How do I get PhpStorm to detect this function will die?
I did try a few items "#return die" or "#die" but these do not appear to be recognized. I also reviewed some documentation here but found nothing useful.
There is no special tags for such stuff in PHPDoc. PhpStorm also does not have any solution to that yet.
https://youtrack.jetbrains.com/issue/WI-10673 -- watch this ticket (star/vote/comment) to get notified on any progress.
UPDATE 2020-10-20:
The aforementioned ticket has been implemented and such functionality is now available since PhpStorm 2020.1.x version.
It is implemented using Advanced Metadata functionality (by creating separate PHP-like file for IDE eyes only): https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html#define-exit-points
<?php
namespace PHPSTORM_META {
exitPoint(\App\PageFlow::exitApplication());
}
Another example: as a result, the terminate() call with the bar argument provided will act as an exit point (another value will not trigger this). The last line of the run method will therefore be treated as unreachable:
exitPoint(Application::terminate('bar'));
P.S. From PhpStorm 2020.3 (to be released at some point in December or so this year) and using PHP Language Level = 8.0 you will be able to use PHP 8-style attribute #[NoReturn] right in your code instead of separate Advanced Metadata file (see WI-55531 (actual/original implementation) and WI-56103 (new attribute name) tickets).
I have a CodeIgniter 3.1.11 project that I wanted to implement an exitPoint on my SendJsonResponseAndDie() method which is in my myproject/ci/application/helpers/format_helper.php file.
For me, the solution was as simple as creating a meta directory in myproject, then creating a .phpstorm.meta.php file with the following contents:
myproject/meta/.phpstorm.meta.php:
<?php
namespace PHPSTORM_META {
function exitPoint($functionReference) {
return "exitPoint " . $functionReference;
}
exitPoint(\SendJsonResponseAndDie());
}
Hey presto, the "unreachable statement" text appears whenever I mouseover code that occurs after the function call anywhere in the project.
I wish, though, that the lines of code that cannot be reached would be dimmed so that I am visually drawn to the problem instead of requiring my hover event.
Some additional reading not mentioned in #LazyOne's answer: https://github.com/JetBrains/phpstorm-stubs/blob/master/meta/.phpstorm.meta.php

Trying to throw an exception gives fatal error with php cli

I'm trying to throw new Exception(...) in a script written for PHP CLI.
This is the error:
PHP Fatal error: require(): Failed opening required '/Exception.php'
(include_path='.:/usr/share/php:/usr/share/pear') in /file.php
This is the line that refers to:
if (!file_exists($path)) {
if (!mkdir($path)) {
throw new Exception('Unable to create directory: ' . $path);
}
}
Is this a config issue or is something else happening to cause this?
I've not written anything before to be used with PHP CLI so not sure on a lot of things like this.
Thanks for all help.
This error has nothing to do with php cli. Also it has nothing to do with Exceptions.
The message error you receive is due to the fact that in your code you have a sentence like:
<?php
require '/Exception.php';
And the file Exception.php doesn't exists in your root.
For using php Exceptions you don't need to include any require. If you remove the above sentence, your error code will desapear.

Does ActionScript have an equivalent of a "core dump"?

Here's my situation: I'm working on an AS3-based game and I'd like to have a "Report a problem!" function within the game so that users can submit feedback to me.
When my user reports a problem, I'd like to get as much information as I can about the state of their game; basically what objects are in memory, what the values are of all those variables inside all those objects; essentially the same information I can get when I hit a breakpoint in the debugger.
Is there a simple way of doing this? I'm afraid that I'll spend several days trying to write a bunch of functions that gets all this information for me, only to have somebody tell me afterwards, "Oh, why didn't you just call ASUtils.getSnapshot()"?
There is no generic way in AS3 to dump the state of your variables, but there are several things we do that you might find useful:
Capture a log of recent click activity. Use stage event listener to log clicks and trace the object "path" up the parent chain to the stage. The object path is just all the DisplayObject names, like: screenMain.dialogBuyItem.buttonBuy
Capture a screenshot, reduce it to a small thumbnail, JPEG encode it, and upload it to your server along with their feedback. We also do this when there is an exception (see #4). as3corelib has JPEG encoding functions in com/adobe/images
Write a command-line pearl or PHP script you can run on your AS3 code before you publish it that will inject call tracing at the top of each function call. This allows call history to be logged. While it's not as good as a full stack, it will give you some indication of what your code has been doing recently.
Trap asserts and unhandled exceptions and log them to your server with click activity and call history trace. Unhandled exception listeners are new in flash 10.1, but most users have this feature. You can check for that support and add a listener like this:
// Check for the presence of the Flash 10.1 global Error event (exception) handler class.
// If it exists, we'll listen for it and it will allow us to report errors to our server.
if ( loaderInfo.hasOwnProperty( 'uncaughtErrorEvents' ) )
loaderInfo.uncaughtErrorEvents.addEventListener( "uncaughtError", onUncaughtError ); // UncaughtErrorEvent.UNCAUGHT_ERROR
If you have global state variables that you want to log with feedback, you can write a function to dump them to a string for uploading with the user feedback. While you can enumerate class and object properties using for each, this only works for public members. Google around and you'll find some functions people have written to dump objects and array data recursively using this enumeration trick.
i'd like to add it as a comment, but don't want to lose code formatting
this is what i'm using to trace complex objects:
private function parseObject(o:Object, prefix:String = '>'):String {
var retStr:String = '';
for (var s:String in o) {
retStr += prefix + s + ' = ' + o[s] + '\n';
if (typeof(o[s]) == 'object') {
retStr += parseObject(o[s], prefix + '>');
}
}
return retStr;
}
hope it'd be helpful