Symfony2 StopPropagation() on event kernel.exception fail - events

In symfony2.3, I added an eventListener on kernel.exception as a service : my listener is triggered when kernel exception occured but the StopPropagation does not stop the propagation of the event ... and so the kernel catch the event and display error page
After calling StopPropagation(), I tested the value of isPropagationStopped() : 1
Vn/CommonBundle/Resources/config/services.yml :
kernel.listener.vn.MongoCursorException:
class: Vn\CommonBundle\Listener\VnExceptionListener
scope: request
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
Vn/CommonBundle/VnExceptionListener.php :
public function onKernelException(GetResponseForExceptionEvent $event){
$exception = $event->getException();
if ($exception->getCode()=='11000') {
$attributes = (array) $event->getRequest()->attributes;
$attributes['Mongoerror']=$exception->getCode();
$event->getRequest()->attributes= new ParameterBag($attributes);
$event->stopPropagation();
}
Thanks by advance for your help !

Related

Unexpected error during jasmine test (with observable)

I wrote a test for the following method:
private _segmentationStatus$: Subject<string> = new Subject();
public readonly segmentationStatus: Observable<string> = this._segmentationStatus$.asObservable();
/**
* Get the status from the segmentation service.
*/
public getStatus() {
const segmentationId: string = this._segmentationIdService.segmentationId;
const segmentationStatusUrl = `${this.getSegmentationStatusUrl}/${segmentationId}/status`;
this._http
.get(segmentationStatusUrl, { responseType: 'text' })
.subscribe({
next: () => {
this._loggerService.trackTrace(`Segmentation status: ${status}`, LogSeverity.Verbose);
this._segmentationStatus$.next(status);
},
error: (error) => {
this._messageService.emitMessage(new Message(MessageCode.ErrorGetStatus, error));
this._loggerService.trackException(error);
this._segmentationStatus$.error(error);
}
});
}
To test the method I started to write a test as below:
fit('should emit a message if the request failed', done => {
let messageReceived: Message;
spyOn((service as any)._messageService, 'emitMessage').and.callFake(message => {
messageReceived = message;
});
service.segmentationStatus.subscribe({
error: () => {
expect(messageReceived.messageCode).toBe(MessageCode.ErrorGetStatus);
done();
}
});
spyOnProperty(
(service as any)._segmentationIdService,
'segmentationId',
'get'
).and.returnValue('id');
service.getStatus();
httpTestingController
.expectOne(`${service.getSegmentationStatusUrl}/id/status`)
.flush('{}', { status: 500, statusText: 'status' });
});
If I use the debugger the flow of the program and test is as expected. I see the emitted message and the error handler in the unit test is called. However, after the error handler in the unit test completes the line this._segmentationStatus$.error(error); in the productive code throws another error, which is not handled. Thus the tests fails with the message Uncaught [object Object] thrown.
I`ve read the RxJS documentation and googled the problem, but was not able to figure out what I need to do pass the test. Any help to point out where I did the mistake would be highly appreciated.
I've found the problem; there was another subscriber to segmentationStatus which did not handle the error. As nobody "trapped" the exception it bubbled up and was re-thrown. As explained in On The Subject Of Subjects (in RxJS).

How to handle solr disconnection in codeigniter

I implement search functionalities with the help of solr via solarium in CodeIgniter.
I'm starting my website without solr connection (i.e. If the solr connection is stopped), My website throws the below warning message,
An uncaught Exception was encountered
Type: Solarium\Exception\HttpException
Message: Solr HTTP error: HTTP request failed, Failed to connect to localhost port 8983: Connection refused
Filename: C:\wamp\www\project-folder\project-name\vendor\solarium\solarium\src\Core\Client\Adapter\Curl.php
Line Number: 170
My doubt is if any chance to add exception handling in solr connection.
That means, If solr status is true it works as it is. If the solr status is false (Not in connection) the error warning is not displayed.
This above scenario is possible or not by using exception handling.
Update
My controller page,
function __construct()
{
parent::__construct();
$this->config->load('solarium');
$this->client = new Solarium\Client($this->config->item('solarium_endpoint'));
}
public function solrQuery()
{
$query = $this->client->createSelect();
$query->setStart(0)->setRows(1000);
// get the facetset component
$facetSet = $query->getFacetSet();
$facetSet->createFacetField('product_category_1')->setField('product_category_1');
$categories_data = $this->client->select($query);
}
Surround the relevant bits of code that throw exceptions in a try-catch block like so:
function __construct() {
parent::__construct();
$this->config->load('solarium');
try {
$this->client = new Solarium\Client($this->config->item('solarium_endpoint'));
} catch (\Exception $e) {
show_error($e->getMessage());
}
}
public function solrQuery() {
try {
$query = $this->client->createSelect();
$query->setStart(0)->setRows(1000);
// get the facetset component
$facetSet = $query->getFacetSet();
$facetSet->createFacetField('product_category_1')->setField('product_category_1');
$categories_data = $this->client->select($query);
} catch (\Exception $e) {
show_error($e->getMessage());
}
}
Of course you don't have yo use show_error() and can instead return false, or set your own headers and your own message.

Laravel Echo not listening for pusher events

Trying to create a kind of chat app with laravel and vuejs.
Once the message is sent, I fire the event from laravel which reflects on the pusher debug console with the right event class but the listen callback from vuejs is not called at all.
created () {
window.Echo.channel('chat')
.listen('MessageSent', (e) => {
console.log(e); //not getting this
this.sentMessages.push({
message: e.message.message,
user: e.user
});
});
},
Below is a screenshot of the debug console from pusher
see the image here as am told I can't embed images yet
Try this:
created () {
window.Echo.channel('chat')
.listen('App\\Events\\Chats\\MessageSent', (e) => {
console.log(e);
this.sentMessages.push({
message: e.message.message,
user: e.user
});
});
},
By default, Laravel will broadcast the event using the event's class name. However, you may customize the broadcast name by defining a broadcastAs method on the event:
public function broadcastAs()
{
return 'server.created';
}
The above was copy pasted from Laravel Broadcast Name
My recommendation:
I have always used private channels for chat and you must too.
Read here why

How do I catch a specific exception thrown by the Laravel 5.6 Queue's failed method?

My handler() throws a SalesforceException. I want to watch that and log the particular error message from the it, using the failed() method on the Queue in Laravel 5.6. If I do the below, I am getting the error:
Error
[2018-04-17 00:18:12] local.ERROR: Type error: Argument 1 passed to App\Listeners\SyncNewsletterSignupToSalesforce::failed() must be an instance of Exception, instance of App\Events\NewsletterSignup given {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Type error: Argument 1 passed to App\\Listeners\\SyncNewsletterSignupToSalesforce::failed() must be an instance of Exception, instance of App\\Events\\NewsletterSignup ...
Code
public function failed(Exception $e)
{
try {
} catch(SalesforceException $e)
{
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
logger($responseBodyAsString);
}
}
Set up a listener in your AppServiceProvider to listen for failed jobs from the queue:
public function boot() {
Queue::failing(function (JobFailed $event) {
// $event->connectionName
// $event->job
// $event->exception
// check for the specific exception type
if ($event->exception instanceof SalesforceException) {
// do something
}
});
}
More here on failed job events.

IONIC 3 : Publish event from handle error function in rest provider

I hope we could help me. I'am a beginner with ionic framework.
I have an app with a restfull api server side. I make a rest provider client to interact with this api :
In this provider i have a function to handle error in each request. When the status code is 401 i would like to publish an event "session:expired" to catch it in my app.component.ts to redirect user to login page.
For example a sample of my code :
#Injectable()
export class RestProvider {
.......
myApiUrl = https://......
constructor(public http: HttpClient,
public loadingCtrl: LoadingController,
public loader: LoaderProvider,
public events: Events) {
}
/***
* API REST FOR USER WEBSERVICE
*/
getUsers(params=null): Observable<Student[]> {
return this.http.get(this.myApiUrl + "/users", { params: params, headers:this.customHeader })
.map(this.extractData)
.catch(this.handleError);
}
...........
private extractData(res: Response) {
console.log(res);
let body = res;
return body || { };
}
private handleError (error: Response | any) {
...
if(error.status == 401)
{
console.log("Status Error 401 : " + error.status);
this.events.publish('session:expired');
}
return ......
}
My problem : the "this.event.publish" in the handleError(or extractData) function doesn't work and break/freeze my App with no error in console ??
if i publish an event in the getUsers function that's work(but no interest) :
getUsers(params=null): Observable<Student[]> {
this.events.publish('session:expired');
return this.http.get(this.myApiUrl + "/users", { params: params, headers:this.customHeader })
.map(this.extractData)
.catch(this.handleError);
}
Is it possible to publish event in map or catch function of http object ? maybe i have not the "good practice" ?
Thanks you in advance and sorry for my english :/

Resources