Error opening Laravel project after 30 minutes - laravel-5.1

I am getting errors when reloading the previously opened tab of my Laravel Project on my browser. There is no error on the page, I mean it loads correctly when I opened it half hour ago.
The error says "Trying to get property of non-object"
4/4 ErrorException
Trying to get property of non-object
(View: C:\xampp\htdocs\demo\resources\views\partials\mainheader.blade.php)
(View: C:\xampp\htdocs\demo\resources\views\partials\mainheader.blade.php)
(View: C:\xampp\htdocs\demo\resources\views\partials\mainheader.blade.php)
ADDED: Only suspicious code that might be causing problem on mainheader.blade.php is, I am using {{ Auth::user()->name }}. But I am still confuse how I can Redirect this exception.
What I thought was, it was due to error in session and token expiration, so I added this code to app/Exception/handler.php
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return redirect('error/403')->withErrors(['token_error' => 'Sorry, your session seems to have expired. Please try again.']);
}
But, that was not solved. Could you please so me the right way?

Found my mistake. Actually it was on the route, I should have added middleware for Auth.
Route::get('/home', ['middleware' => 'auth', function () {
return view('home');
}]);
Now, that's good and working.

Related

Getting sometimes double POST request to IIS 10 webserver

Since we migrated to an Amazon EC instance we're getting sometimes double POST requests to our SaaS application. I have no idea where this is coming from and why this is happening. I've been searching and looking at different options, but can't find the root cause. We migrated from IIS7 to IIS10 on a Windows Server 2022 Datacenter.
Here is an example of an SEQ logging session at 1 client:
SEQ Log
You can see the endpoint was requested multiple times (= OK), but there is also a double POST request at 18:19:41 and 18:18:27. This is logged from within the ASP.NET MVC controller. If I look at the IIS 10 logs, I see the same thing. So the request seems to be initiated from the browser and not doubled in the pipeline.
The MVC controller looks something like this (simplified):
if (ViewData.ModelState.IsValid){
try
{
NHibernateSession.Current.Transaction.Begin();
foreach (var item in deliveryDTosToSave){
var delivery = new Delivery
{
//copying over the DTO to the delivery
};
_deliveryRepository.SaveNew(delivery, userCode, item.Index);
}
NHibernateSession.Current.Transaction.Commit();
return RedirectToAction("Add", "Delivery", new { tab, pharmacyId });
}
catch (RuleException ex)
{
NHibernateSession.Current.Transaction.Rollback();
}
}
On the client-side, the javascript to submit is something like this:
$('#formDeliveries').submit(function () {
if (!canSubmit) {return false;}
$("#loading").show();
canSubmit = false;
});
Things I looked for:
user double-clicking on the submit button: we've blocked this through JS after initial submit. I interviewed several users, and they are not double-clicking.
bug in browser: last user I logged in used Edge 107, which is recent. I can't find anything on the matter
HTTPS redirects: the website is HTTPS-only and users have to be authenticated to use it.
HTTP/3 fall-back scenario's: could be possible as we've enabled HTTP/3 when migrating to Amazon. However users are seeing this behaviour only sometimes and not always from the same browser.
We've tried to simulate the behaviour, but cannot find it. We've logged into the users computer and tried to simulated it while looking at the network requests through the developers utils, but cannot simulate it. I was hoping to see it happening live, so we can rule out any javascript items. If the network log in developer tools shows only 1 POST, it probably has to do something with the IIS pipeline.
Any advice would be greatly appreciated.

NestJS microservices error with "No matching message handler"

I'm building an application with microservices communicating through RabbitMQ (request-response pattern). Everything works fine but still I have a problem with error "There is no matching message handler defined in the remote service." - When I send POST to my Client app, it should simply send the message with data through client (ClientProxy) and the Consumer app should response. This functionality actually works, but always only for the second time. I know it sounds strange but on my first POST request there is always the error from Client and my every second POST request works. However this problem is everywhere in my whole application, so the particular POST request is just for the example.
Here is the code:
Client:
#Post('devices')
async pushDevices(
#Body(new ParseArrayPipe({ items: DeviceDto }))
devices: DeviceDto[]
) {
this.logger.log('Devices received');
return this.client.send(NEW_DEVICES_RECEIVED, devices)
}
Consumer:
#MessagePattern(NEW_DEVICES_RECEIVED)
async pushDevices(#Payload() devices: any, #Ctx() context: RmqContext) {
console.log('RECEIVED DEVICES');
console.log(devices);
const channel = context.getChannelRef();
const originalMsg = context.getMessage();
channel.ack(originalMsg);
return 'ANSWER';
}
Client has the RMQ settings with queueOptions: {durable: true} and the consumer as well queueOptions: {durable: true} with noAck: false
Please do you have any ideas what may causes the problem? I have tried sending the data with JSON.stringify and changing the message structure to {data: devices} but the error is still there.
I had same error and finally solve it today.
In my project, there is an api-gateway as a hybrid application to receive requests and pass data to other systems, every second request gives an error like below.
error: There is no matching message handler defined in the remote service.
Then I tried to remove the api-gateway hybrid application scope in the code below, the error is gone, hope this helps you out with this.
// api-gateway main.ts
const app = await NestFactory.create(AppModule);
// run as a hybrid app —→ remove it
app.connectMicroservice({
transport: Transport.RMQ,
noACK: false,
options: {
urls: [`amqp://${rmqUser}:${rmqPassword}#127.0.0.1:5672`],
queue: 'main_queue',
queueOptions: {
durable: false,
},
},
});
// run hybrid app
await app.startAllMicroservices(); —→ remove it
await app.listen(3000);
I solved this issue by placing the #EventPattern decorator on to a #Controller decorator method
I had this error while NOT using RabbitMQ. I found very little help online around this error message outside of it being related to RabbitMQ.
For me it was an issue where I was importing a DTO from another microservice in my microservice's Controller. I had a new DTO in my microservice that has a similar name to one in another microservice. I accidentally selected the wrong one from the automated list.
Since there wasn't any real indicator that my build was bad, just this error, I wanted to share in case others made the same mistake I did.
I encountered this same issue today and could not find any solution online and stumbled upon your question. I solved it in a hacky way and am not sure how it will behave when the application scales.
I basically added one #EventPattern (#MessagePattern in your case) in the controller of the producer microservice itself. And I called the client.emit() function twice.
So essentially the first time it gets consumed by the function that is in the producer itself and the second emit actually goes to the actual consumer.
This way only one POST call is sufficient.
Producer Controller:
#EventPattern('video-uploaded')
async test() {
return 1;
}
Producer client :
async publishEvent(data: VideosDto) {
this.client.emit('video-uploaded', data);
this.client.emit('video-uploaded', data);
}
I've experienced the same error in my another project and after some research I've found out that problem is in the way of distributing messages in RabbitMQ - named round-robin. In my first project I've solved the issue by creating a second queue, in my second project I'm using the package #golevelup/nestjs-rabbitmq instead of default NestJS library, as it is much more configurable. I recommend reading this question

How to get MiniProfiler logs from the redirected request?

I have the MiniProfiler installed in my ASP.NET MVC 3 project running good but i got a problem, the MiniProfiler only shows logs from the last request and some "summary" of the whole site loading.
I have a form that posts to /MyForm and MyForm actionresult redirects to /Show and i get all logs for /Show but not all from /MyForm but i getting a summary how long time the /MyForm taked + the sql questions but i dont get the children logs from it.
Any ideas?
I found the similar issue of not showing the profiler-popup button in page, of a POST request after redirect. In my case, it was because of the result length exceeds the maximum Json string Length. To resolve this I set the size limit as below:
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue
I put it in Application_Start().
I found the response:
In the global.asax, after the call to MiniProfiler.Stop(), add this code to prevent to tell the id of the logs at the ajax response.
//Se faccio il redirect tolgo il render del mini profiler
const string KEY_HEADER_MINIPROFILER = "X-MiniProfiler-Ids";
if (!string.IsNullOrEmpty(Response.RedirectLocation) && Response.Headers.AllKeys.Contains(KEY_HEADER_MINIPROFILER))
{
Response.Headers.Remove(KEY_HEADER_MINIPROFILER);
}
In the next page will be rendered also the log of the page that make the redirect
If you make itself the redirect with a javascript after an ajax request remember to make:
Response.RedirectLocation = "...."

CI 2.0.3 session heisenbug: session is lost after some time 20 minutes, only on server redirect, nothing suspicious in the logs

I can't seem to make any progress with this one. My CI session settings are these:
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 0;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = FALSE;
$config['sess_time_to_update'] = 7200;
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
The session library is loaded on autoload. I've commented the sess_update function to prevent an AJAX bug that I've found about reading the CI forum.
The ci_sessions table in the database has collation utf8_general_ci (there was a bug that lost the session after every redirect() call and it was linked to the fact that the collation was latin1_swedish_ci by default).
It always breaks after a user of my admin section tries to add a long article and clicks the save button. The save action looks like this:
function save($id = 0){
if($this->my_model->save_article($id)){
$this->session->set_flashdata('message', 'success!');
redirect('admin/article_listing');
}else{
$this->session->set_flashdata('message', 'errors encountered');
redirect('admin/article_add');
}
}
If you spend more than 20minutes and click save, the article will be added but on redirect the user will be logged out.
I've also enabled logging and sometimes when the error occurs i get the message The session cookie data did not match what was expected. This could be a possible hacking attempt. but only half of the time. The other half I get nothing: a message that I've placed at the end of the Session constructor is displayed and nothing else. In all the cases if I look at the cookie stored in my browser, after the error the cookie's first part doesn't match the hash.
Also, although I know Codeigniter doesn't use native sessions, I've set session.gc_maxlifetime to 86400.
Another thing to mention is that I'm unable to reproduce the error on my computer but on all the other computers I've tested this bug appears by the same pattern as mentioned above.
If you have any ideas on what to do next, I'd greatly appreciate them. Changing to a new version or using a native session class (the old one was for CI 1.7, will it still work?) are also options I'm willing to consider.
Edit : I've run a diff between the Session class in CI 2.0.3 and the latest CI Session class and they're the same.
Here's how I solved it: the standards say that a browser shouldn't allow redirects after a POST request. CI's redirect() method is sending a 302 redirect by default. The logical way would be to send a 307 redirect, which solved my problem but has the caveat of showing a confirm dialog about the redirect. Other options are a 301 (meaning moved permanently) redirect or, the solution I've chosen, a javascript redirect.

Sencha Touch JSONP error

EDIT:
I came across a confirmation of what I suspected: Using the twitter search API with JSONP causes the problem in isolation, so it seems that something is going wrong with Twitter.
See:
http://search.twitter.com/search.json?q=%23jimromeisburning&callback=dog
About 3/5 times, as of 3:44PM CT on 14 June, Twitter returns garbage. The rest of the time, it returns a valid javascript function call.
I'm using Sencha Touch to make a JSONP request to the Twitter search API, and about 1/100 times, I'm getting a javascript error that kills further polling:
Uncaught SyntaxError: Unexpected token ILLEGAL
So far I've tried the following with no leads:
Wrapping the call to Ext.util.JSONP.request({}) in a try/catch block. Doesn't catch the error (presumably because it's being called from a script tag in an iframe)
Dumping the query parameter passed into JSONP.request to make sure that it's valid. It is.
Looking for a pattern-- it seems to happen at unexpected times. Could be the very first request, or it could be 100 requests down the line.
My best guess is that Twitter is sending back garbage some of the time. That's ok, I just need a way to handle that error. Unfortunately, as far as I can tell, Sencha Touch doesn't have any built-in error handling for its JSONP requests.
Have you seen anything like this before? Do you have any ideas?
Thanks!
Here's what the ornery JSONP script response looks like:
Ext.util.JSONP.callback(�Řo�6ǿ
�`)֥��k�em��+�`�
-�-��RT��w�ɖ���$v�-A^ґ���Ow�|�4Tua*+����ת����Ⱥ��VbšҐ�֡5Ҫ/
芒�[�o�ƌ��NnjE9褪���*��N3�1j;QRǏ®T��E�r4��S
�#��w|��!a.���ġ�%�����#��*����>Z8^_h��녾z>u]�E��ϸ�V��u�k&##k
)Hc}=���;o%�.
�׍���L��5�T�B*�?������{���꒼z�M���.}/dm�=���곒5i�KA��y����Q�n���n����
Һ�x��̼R�N���q�k��<�\+s�*���&[��DCњH�WE�Ƴ���uhj�ڼ����ȋ��,t"�>�'����o�VnK��ⳍ�\�p,'9�
��:~{��"���8n�
�x�ͫK���C�mx(�<�
����3>������B]A_�L�+=�%fY�*1��/���wO�vc�Z8d=)̦1����߳35����-F����.f���D|�.z6����Xs��s\愶 ���M*Z�D�� �7ڈ�)ϗ cA�^9N�n�aN#�w�/^
P��¸-�E�$R�����<�K�n�3A3��򳀇�L+�mI��vՃ�0Ǎ}o���Q��4�����=e��n�q8��ģ�����.�C)s=�:+>�O�h9�C2Q5Y���PA����*�3y1�t�`���g��WǠ�YB�O�/�{+.�[����,ߴ��/�yQ�<t(���|ߥ�G����ݾ�b��ijBS�9��.E�>�D%�I���jz�켻0�q��0`Q��.��.�>88�춖��(i4fȻgW#�aI*�������#���z�j�\5g��\�n���e���c��7�o��w�z�,�|/��+�N�����}�z+v����nd�
NY�R��o�� }��hĚ�;��g�D2��9�����:-e�����^#Ua���j2C��#�U���k�9���I�'�ܐ���/H3�q(��d�<�$����q~͛5��}��V�ft�'U'{���0�����Ø��sC?|B��0I���B�E] %�c��S���6LC�x�Y�EQT�*�Akr��÷OyOn��N�7iSkW` �F�q�!�����+,[���I��1
�i�3C*����_��h�K �� ^�{�V|YìM�7ŬW�t��'��ek��y�lr�l�WM)Đ�>�O���F,`�w��r��6�a�X����B�n�2t�O\�R7��O�n���!`�#
M� i���MU]5_�k�TMR�� 'Z��Y��C�Sn�q.�V��";d�`x��k Β��Mr��/�����٬A��Fq�B|L���>+,B0��R��K�����˵u�_~縫}��Zw����E���7�K����:.�i�n%��4l�/F���������5_�����);
I recently answered a similar question in which the OP was encountering fail whales while using the search API.
I found this question which had some interesting answers regarding error handling in JSONP. To summarize, one approach is to wrap all errors returned by the server in JSON, and another provides a link to jQuery-JSONP, a nice looking reinterpretation of jQuery's JSONP implementation.
Interesting. You would need to override the callback method in the Ext.util.JSONP class, and wrap the line which calls the callback, in a try/catch block. Then in the catch block try and call an errorCallback (which you need to define in your actual JSONP request).
Ext.util.JSONP.callback = function(json) {
try {
this.current.callback.call(this.current.scope, json);
} catch(e) {
this.current.errorCallback.call(this.current.scope);
}
document.getElementsByTagName('head')[0].removeChild(this.current.script);
this.next();
};

Resources