How to Have a Detailed Trace of a Slim Application Error - slim

I have 10000 lines of code outlining routes of my API implemented using the Slim Framework. However, I got an error message preg_match(): Compilation failed: two named subpatterns have the same name at offset 89. The problem is, I got the stack trace referring to this statement preg_match('/cost-centers...', '/overview/funds...', NULL) at the Slim Route.php. Now that my URLs are lengthy, I can't pinpoint which of the URLs have the same name.
Is there any way to have a more detailed stack trace instead of displaying these shortened format?

Thanks to mgansler for this tip.
I just used a custom error handler with PHP Exception::getTrace() function. I also turned the Slim's default debugging off to ensure that the custom error handler is invoked.
Code goes like this:
$app = new \Slim\Slim(array(
'debug' => false
));
$app->error(function (\Exception $e) use ($app) {
//enter manipulation of $e->getTrace()
//or just var_dump($e->getTrace()) but the format would be chaotic
});

Related

Stop huge error output from testing-library

I love testing-library, have used it a lot in a React project, and I'm trying to use it in an Angular project now - but I've always struggled with the enormous error output, including the HTML text of the render. Not only is this not usually helpful (I couldn't find an element, here's the HTML where it isn't); but it gets truncated, often before the interesting line if you're running in debug mode.
I simply added it as a library alongside the standard Angular Karma+Jasmine setup.
I'm sure you could say the components I'm testing are too large if the HTML output causes my console window to spool for ages, but I have a lot of integration tests in Protractor, and they are SO SLOW :(.
I would say the best solution would be to use the configure method and pass a custom function for getElementError which does what you want.
You can read about configuration here: https://testing-library.com/docs/dom-testing-library/api-configuration
An example of this might look like:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
You can then put this in any single test file or use Jest's setupFiles or setupFilesAfterEnv config options to have it run globally.
I am assuming you running jest with rtl in your project.
I personally wouldn't turn it off as it's there to help us, but everyone has a way so if you have your reasons, then fair enough.
1. If you want to disable errors for a specific test, you can mock the console.error.
it('disable error example', () => {
const errorObject = console.error; //store the state of the object
console.error = jest.fn(); // mock the object
// code
//assertion (expect)
console.error = errorObject; // assign it back so you can use it in the next test
});
2. If you want to silence it for all the test, you could use the jest --silent CLI option. Check the docs
The above might even disable the DOM printing that is done by rtl, I am not sure as I haven't tried this, but if you look at the docs I linked, it says
"Prevent tests from printing messages through the console."
Now you almost certainly have everything disabled except the DOM recommendations if the above doesn't work. On that case you might look into react-testing-library's source code and find out what is used for those print statements. Is it a console.log? is it a console.warn? When you got that, just mock it out like option 1 above.
UPDATE
After some digging, I found out that all testing-library DOM printing is built on prettyDOM();
While prettyDOM() can't be disabled you can limit the number of lines to 0, and that would just give you the error message and three dots ... below the message.
Here is an example printout, I messed around with:
TestingLibraryElementError: Unable to find an element with the text: Hello ther. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
...
All you need to do is to pass in an environment variable before executing your test suite, so for example with an npm script it would look like:
DEBUG_PRINT_LIMIT=0 npm run test
Here is the doc
UPDATE 2:
As per the OP's FR on github this can also be achieved without injecting in a global variable to limit the PrettyDOM line output (in case if it's used elsewhere). The getElementError config option need to be changed:
dom-testing-library/src/config.js
// called when getBy* queries fail. (message, container) => Error
getElementError(message, container) {
const error = new Error(
[message, prettyDOM(container)].filter(Boolean).join('\n\n'),
)
error.name = 'TestingLibraryElementError'
return error
},
The callstack can also be removed
You can change how the message is built by setting the DOM testing library message building function with config. In my Angular project I added this to test.js:
configure({
getElementError: (message: string, container) => {
const error = new Error(message);
error.name = 'TestingLibraryElementError';
error.stack = null;
return error;
},
});
This was answered here: https://github.com/testing-library/dom-testing-library/issues/773 by https://github.com/wyze.

Adding message to IMAP folder using ZF3

I am trying to add a new message to IMAP folder using Zend Framework 3.
The code I use is the following:
...
$draftMessage = new \Zend\Mail\Storage\Message([
'headers' => [
'subject' => 'voyteck0#gmail.com',
],
'content' => 'ala ma kota',
]);
[valid-imap-connection]->appendMessage($draftMessage, 'Drafts', [\Zend\Mail\Storage::FLAG_DRAFT]);
...
However I always get an exception thrown:
Zend\Mail\Storage\Exception\RuntimeException:'cannot create message, please check if the folder exists and your flags' thrown in /.../zendframework/zend-mail/src/Storage/Imap.php(480)
I have also used in here a pseudo-element [valid-imap-connection] not to blur the problem - but the connection is working fine (retrieves messages, sends them, moves between folders etc.)
The folder exists - I have done some debuging even within ZF already and found out that in that line 480 the command returns NULL on the above code. If I change the folder into non-existing one - it returns false.
The Exception itself is thrown once (! result) - so null is also true for this condition.
However even if I am removing the code that throws exception (And the code completes execution with that NULL value) - still the message is not appearing in the folder (checking directly on the disk). There's nothing interesting in Dovecot logs (apart from the fact the connection is successfully established).
Any ideas highly welcome :)
I think the problem was with 2 things:
I should have used \Zend\Mail\Message class (not the ...\Storage... one)
The draftMessage should be a string version (actually dunno why - since appendMessage already uses toString() function)
So the code that works is following:
...
$draftMessage = new \Zend\Mail\Message();
$draftMessage->setSubject('voyteck0#gmail.com');
$draftMessage->setBody('ala ma kota');
[valid-imap-connection]->appendMessage($draftMessage->toString(), 'Drafts', [\Zend\Mail\Storage::FLAG_DRAFT]);
...

returning error message to front end Scala Play

I need to send an error status to the front end using Scala play. Ok is to say all is ok but which one is for error? Can this be done from any Scala method I created?
thanks
It can be done from any method, you just need to use correspondent Result. For the general server error it is InternalServerErrorlike
def index = Action {
InternalServerError("Some error happens")
}
You can find more results here: https://playframework.com/documentation/2.6.7/api/scala/index.html#play.api.mvc.Results
The examples are:
InsufficientStorage //507
Locked //423
You can also send your own state as simple as
new Status(500) //aka InternalServerError

Zend Framework - ZFDebug - Log - Log Custom Errors

When using ZFDebug, is it possible to add custom messages to the 'Log' tab?
So you could use something like:
$this->log('Error: Couldn't find the user');
Has anyone managed to achieve this?
I have never used ZFDebug before and wasn't aware of it. Your post piqued my interest, so I installed it and have been trying to achieve what you want to do. I will probably add it to my dev toolbox as I use ZF a lot.
You can achieve what you want by using the mark() method of ZFDebug_Controller_Plugin_Debug_Plugin_Log which takes two arguments. The first is the message you want to send and the second is a boolean which, when set to true (default is false), will send your message to the 'log' tab.
The following code worked for me:-
$debug = Zend_Controller_Front::getInstance()
->getPlugin('ZFDebug_Controller_Plugin_Debug');
$logger = $debug->getPlugin('log');
$logger->mark('Logging a message now', true);
Or to use your example (with the syntax error fixed :) )
$logger->mark("Error: Couldn't find the user", true);
As you can see this produced the desired output:-
Not quite as simple as you wanted, I know, but it's close and you could always wrap it in a function.

Validation / Error Messages in ASP.Net MVC 2 View Unrelated to a Property

What pattern can I use to display errors on an MVC 2 view that are not related to a single property?
For example, when I call a web service to process form data, the web service may return an error or throw an exception. I would like to display a user-friendly version of that error, but have no logical means to relate the error to any given property of the model.
UPDATE:
Trying to use this code as suggested, but no summary message is displayed:
MyPage.spark:
Html.ValidationSummary(false, "Oopps it didn't work.");
Controller:
ViewData.ModelState.AddModelError("_FORM", "My custom error message.");
// Also tried this: ViewData.ModelState.AddModelError(string.Empty, "My custom error message.");
return View();
UPDATE 2
What does this mean?
next to each field.
Instead of always displaying all
validation errors, the
Html.ValidationSummary helper method
has a new option to display only
model-level errors. This enables
model-level errors to be displayed in
the validation summary and
field-specific errors to be displayed
next to each field.
Source: http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc#_TOC3_14
Specifically, how does one add a model level error (as opposed to a field-specific error) to the model?
UPDATE 3:
I noticed this morning that Html.ValidationSummary is not displaying any errors at all, not even property errors. Trying to sort out why.
Simply adding a custom error to the ModelState object in conjunction with the ValidationSummary() extension method should do the trick. I use something like "_FORM" for the key... just so it won't conflict with any fields.
As far as patterns go, I have it setup so that my Business Logic Layer (called via services from the controller) will throw a custom exception if anything expected goes wrong that I want to display on the view. This custom exception contains a Dictionary<string, string> property that has any errors that I should add to ModelState.
HTHs,
Charles